JavaScript function call rules

Source: Internet
Author: User
Tags jquery library
JavaScript function call Rule 1
(1) Global function call: function makeArray (arg1, arg2) {return [this, arg1, arg2];} this is the most common function definition method. I believe that JavaScript learners are familiar with calling JavaScript. The call code is as follows: makeArray ('one', 'two'); // => [window, 'one', 'two']
This method can be called globally. Why is it a global function? Because it is a global Object window method, we can use the following method to verify: alert (typeof window. methodThatDoesntExist); // => undefined
Alert (typeof window. makeArray); // => function
Therefore, the method we used to call makeArray is the same as the method called below window. makeArray ('one', 'two'); // => [window, 'one', 'two']



JavaScript function call Rule 2
(1) object method call: // creating the object var arrayMaker = {someProperty: 'Some value here ', make: makeArray };
ArrayMaker. make ('one', 'two'); // => [arrayMaker, 'one', 'two'] // or call it using the following method: arrayMaker ['make'] ('one', 'two'); // => [arrayMaker, 'one', 'two']

The difference is that the value of this is changed to the object itself. You may wonder why the original function definition has not changed, but this has changed?
Very good. It is correct to have doubts. This involves the way functions are passed in JavaScript. A function is a standard data type in JavaScript, which is actually an object. you can pass them or copy them. as if the list of function associated parameters and function bodies are copied and assigned to the make attribute in arrayMaker, it is like defining an arrayMaker: var arrayMaker = {someProperty: 'Some value here ', make: function (arg1, arg2) {return [this, arg1, arg2] ;}};


If you do not understand the call rule 2, various bugs are often encountered in the event processing code. For example: <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 ');
Button1.onclick = buttonClicked; button2.onclick = function () {buttonClicked () ;}; </script> clicking the first button will display "btn1" because it is a method call, this is the object (Button element ). Clicking the second button will display "window", because buttonClicked is directly called (unlike obj. buttonClicked (), which is the same as the third button. therefore, the result of clicking the third button is the same as that of the second button.
So please note: button1.onclick = buttonClicked; button2.onclick = function () {buttonClicked () ;}; this points to a different one.

JavaScript function call rule 3
Of course, if you are using a jQuery library, you don't have to consider that much. It will help override the value of this to ensure that it contains references to the current event source element. // Use jQuery $ ('# btn1'). click (function () {alert (this. id); // jQuery ensures 'eas' will be the button });
So how does jQuery reload the value of this? The answer is: call () and apply ();
When the function is used more and more, you will find that the this you need is not in the same context, which leads to an exception in communication.
In Javascript, functions are also objects. Function objects include some predefined methods. Two of them are apply () and call (). We can use them to reset the context of this.
<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 ');
Button1.onclick = buttonClicked; button2.onclick = function () {buttonClicked. call (this); // btn2}; </script>

JavaScript function call Rule 4
(1) constructor I don't want to study the type definition in Javascript in depth, but at this moment we need to know that there are no classes in Javascript, and any custom type requires an initialization function, defining Your type using a prototype object (as an attribute of the initialization function) is also a good idea. Let's create a simple type // declare a constructor function ArrayMaker (arg1, arg2) {this. someProperty = 'whatever'; this. theArray = [this, arg1, arg2];} // declare the instantiation method ArrayMaker. prototype = {someMethod: function () {alert ('memethod called');}, getArray: function () {return this. theArray ;}};
Var am = new ArrayMaker ('one', 'two'); var other = new ArrayMaker ('first', 'second ');
Am. getArray (); // => [am, 'one', 'two'] other. getArray (); // => [other, 'first', 'second']
It is very important and worth noting that the new operator appeared before the function call. Without that, your function is like a global function, all the attributes we created will be created on the Global Object (window), and you don't want to do that. In addition, because there is no return value in your constructor, if you forget to use the new operator, some of your variables will be assigned undefined.
Therefore, the constructor function is a good habit of starting with an uppercase letter, which serves as a reminder so that you do not forget the new operator before calling it. in this way, the code in the initialization function is similar to the initialization function you write in other languages. the value of this will be the object you will create.


SummaryI hope to help you understand the differences in function calling methods and keep your JavaScript code away from the bugs. Knowing the value of this is the first step to avoid bugs.
Related Article

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.