JavaScript function this call rule

Source: Internet
Author: User

This Javascript keyword is widely used in the source code of www.21kaiyun.com.

JavaScript function call Rule 1

(1) Global function call:

Function makeArray (arg1, arg2 ){

Return [this, arg1, arg2];

}

This is the most common way to define functions. 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 method of the Global Object window,

We can verify it using the following method:

Alert (typeof window. methodThatDoesntExist );

// => Undefined

Alert (typeof window. makeArray );

// => Function

Therefore, the method 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 use the following method to call:

ArrayMaker ['make'] ('one', 'two'); // => [arrayMaker, 'one', 'two']

Here is the difference from the previous one. 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 how functions are passed in JavaScript,

A function is a standard data type in JavaScript,

An object. You can pass them or copy them.

As if the list of function associated parameters and function bodies are copied,

The property make is assigned to arrayMaker. It is like defining an arrayMaker as follows:

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 ('tn1 ');

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 and this is the object (Button element) to which it belongs ).

Clicking the second button will display "window", because buttonClicked is directly called (unlike obj. buttonClicked ()),

This is the same as the third button, where the event handler function is directly placed in the tag. 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 difference.

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 ('tn1 ');

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 the moment we need to know that there are no classes in Javascript,

In addition, any custom type requires an initialization function. Using a prototype object (as an attribute of the initialization function) to define your type 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.

Summary

I hope you can understand the differences in function calling methods through these methods,

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.