Several methods of calling functions in JavaScript

Source: Internet
Author: User

When you add a new API feature to your browser, although this API provides more functionality and permissions, I think they may be more confusing to my project, whether it's an API issue or a project-writing idea, we can all try to use it, and you're bound to encounter error codes that don't match your program. Run these APIs using Try/catch, which makes the code cleaner and has fewer side effects.

A secure call function method in JavaScript


We output a message to the user at the console.

The code is as follows Copy Code

function attempt (FN, args, binding) {
try {
return fn.apply (binding, args);
catch (e) {
Console.log (' Exception, fix me please ', e);
}
}
Use it!
Attempt (function () {
/* Volatile Stuff * *
}, [' Argone ', Somevar], this);


Provides features, parameters, and combinations and all of your settings. You can use anonymous functions, function names, whatever. You don't need to add try/catch blocks around yourself. There's nothing groundbreaking in the above code, but it's safe and convenient!

In one use method call syntax, like obj.myfunction () or obj[' MyFunction '] (), at which point the value of this is obj

This is the main source of bugs in the event handling code, and look at these examples

  code is as follows copy code

<input type= "button" value= "button 1" id= "btn1"  />
<input Type= "button" value= "button 2" id= "btn2"  />
<input type= "button" value= "button 3" id= "Btn3"   Onclick= "buttonclicked ();" />
 
<script type= "Text/javascript"
Function buttonclicked () {
    var Text = (this = = window)? ' Window ': this.id;
    alert (text);
}
var button1 = document.getElementById (' btn1 ');
var button2 = document.getElementById (' btn2 ');
 < br> Button1.onclick = buttonclicked;
Button2.onclick = function () {   buttonclicked ();  };
</script>

Clicking on the first button will show "BTN" because it is a method call, this is the object (button element) Click the second button will display "window" because buttonclicked is called directly (unlike obj.buttonclicked ().) This is the same as our third button, where the event handler is placed directly in the label. So click on the third button and the result is the same as the second one.
Using a JS library like jquery has the advantage that when an event handler is defined in jquery, the JS library helps rewrite the value of this to ensure that it contains a reference to the current event source element.

The code is as follows Copy Code

Using jquery
$ (' #btn1 '). Click (function () {
alert (this.id); JQuery ensures ' this ' would be the button
});

How does jquery overload the value of this? Continue Reading


Jsavacript function Call Rule 3

We can use Myfunction.apply (obj) or myfunction.call (obj) if we want to overload the value of this if we do not copy the function to a method.

Construction device
I don't want to delve into the definition of types in JavaScript, but at the moment we need to know that there are no classes in JavaScript, and that any custom type requires an initialization function, and it's a good idea to use a prototype object (as an attribute of the initialization function) to define your type. Let's create a simple type

The code is as follows Copy Code

Declaring a constructor

function Arraymaker (arg1, arg2) {
This.someproperty = ' whatever ';
This.thearray = [This, arg1, arg2];
}
Declaring the instantiation method
Arraymaker.prototype = {
Somemethod:function () {
Alert (' SomeMethod called ');
},
Getarray:function () {
return this.thearray;
}
};

var am = new Arraymaker (' One ', ' two ');
var other = new Arraymaker (' A ', ' second ');

Am.getarray ();
=> [AM, ' one ', ' two ']

  

A very important and noteworthy is the new operator that appears in front of the function call. Without that, your function is like a global function, and the attributes we create will be created on the Global Object (window), and you don't want that, and the other topic is, because there is no return value in your constructor, So if you forget to use the new operator, it will cause some of your variables to be assigned to undefined. For this reason, constructor functions begin with uppercase letters as a good habit, which can be used as a reminder that you should not forget the new operator before you call.
With such caution, the code in the initialization function is similar to the initialization function you write in other languages. This value will be the object you will create.


In functions that are not called directly by an explicit owner object, such as MyFunction (), the value that causes this is the default object (the window in the browser).

Function call
Let's now create a simple object, using the Makearray function as one of its methods, we'll use JSON to declare an object, and we'll call this method

The code is as follows Copy Code
Creating the Object
var arraymaker = {
Someproperty: ' Some value here ',
Make:makearray
};

Invoke the Make () method
Arraymaker.make (' One ', ' two ');
=> [Arraymaker, ' One ', ' two ']
Alternative syntax, using square brackets
arraymaker[' make '] (' One ', ' two ');
=> [Arraymaker, ' One ', ' two ']

  


See the difference here, the value of this becomes the object itself. You may be wondering why the original function definition did not change, and why it is not window. Well, that's how the function is passed in the Jsavacript, the function is a standard data type in JavaScript, Exactly an object. You can pass them on or copy them. It's like the whole function. The list of parameters and function bodies are copied and assigned to the attribute make in Arraymaker, which is like defining a arraymaker:

The code is as follows Copy Code

var arraymaker = {
Someproperty: ' Some value here ',
Make:function (Arg1, arg2) {
return [This, arg1, arg2];
}
};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.