JavaScript beginners MUST See "this"

Source: Internet
Author: User

Translator by: JavaScript is this much different in object-oriented languages such as Java this , and bind() call() apply() functions are further extended to be more this flexible.

Original: Javascript:the Keyword ' this ' for beginners

Translator: Fundebug

In order to ensure readability, this paper uses free translation rather than literal translation. In addition, the copyright of this article belongs to the original author, translation is only used for learning.

If you don't understand JavaScript's keywords this deeply enough, sometimes you fall into unexpected pits. Here we summarize 5 general rules to help you decide this what to point to. While not all the cases are included, these rules can be used to correctly infer most of the daily situations.

    1. thisis usually determined by the execution environment of the function, that is, to see how the function is called;
    2. Each invocation of the same function this may point to a different object;
Global Object

Open the Chrome browser developer panel (Windows:ctrl + Shift + j) (Mac:cmd + Option + j) and enter:

Console.log (this);

See what's out there?

Window {}

windowObject! Because at the global scope, point to the this global object. The global object is the object in the browser window .
To give you a clearer understanding this of why it points window to objects, let's look at another example:

var myName = ' Brandon ';

We can access its value by typing in the console myName :

myname//output ' Brandon '

In fact, all variables that are globally defined are bound to window objects. Let's do the following tests:

window.myname//output ' Brandon ' window.myname = = = myname//Output true

Now we'll this put it inside the function to see what it does.

function Test () { return this ;} Test ();

You will find this objects that still point to the global window . Because this the keyword is not inside a declared object, it points to the global object by default window . This may be a bit difficult for most beginners to understand. When you finish reading this article, you will be enlightened.
Note: If in the strcit mode, the above example this is undefined .

Declared objects (declared object)

When this a keyword is used inside a declared object, its value is bound to the this nearest parent object that called the function. We use examples to illustrate this problem:

var person = { First : ' John ', last : ' Smith ', full : function () { console.log (This.first + "+ this.last); }; Person.full (); //Output ' John Smith '

In the function of the declared object person full , the nearest parent of the function being this called is, this full person Therefore, this pointing person .

To get a better description of this what is actually pointing to person the object, you can copy the following code to the browser console and this print it out.

var person = { First : ' John ', last : ' Smith ', full : function () { console.log (this); }}; Person.full (); //Output Object {first: "John", Last: "Smith", full:function}

Let's look at a more complicated example:

var person = { first: last: full : function ( Span class= "built_in" >console.log (this.first + this.last); }, persontwo: { first: Span class= "attr" >last: ' Jones ', full: function ( console.log (this.first + "+ This.last); } }};

Here we have nested objects, at this point, to this whom? Let's print it out and take a look at it:

Person.full (); //Output ' John Smith 'person.personTwo.full (); //Output ' Allison Jones '

You will find satisfying the rule we described earlier: its value is bound to the nearest parent of the called this function.

newKey words

When new a new object is built using the keyword, this it is bound to the new object. Let's look at an example:

function Car (make, model) { this.make = make; This.model = model;};

According to the first rule, you might infer that you are pointing to a this global object. But if we use the new keyword to declare a new variable, Car the function this will bind a new empty object, and then initialize this.make this.model the value.

var myCar = New Car (' Ford ', ' Escape '); Console.log (myCar); //Output Car {make: "Ford", Model: "Escape"}

call, bindAnd apply

We can display the call() bind() apply() binding object that is set in, this . These three functions are very similar, but we need to pay attention to their tiny differences.

Let's look at an example:

function Add (C, D) { console.log (this.a + this.b + C + d);} Add (3,4); //Output NaN

addfunction output NaN , because this.a and this.b undefined.

Now we introduce the object and use call() and apply() to invoke:

function Add (C, D) { console.log (this.a + this.b + C + d);} var ten = {A: 1, B: 2}; Add.call (Ten, 3, 4); //Output tenadd.apply (Ten, [3,4]); //Output ten

When we use it add.call() , the first parameter is the this object that needs to be bound, and the rest is the add function's original argument.
So, this.a point ten.a , this.b Point ten.b . add.apply()Similarly, in addition to the second argument is an array that is used to store add the parameters of the function.

bind()function and call() similar, but the bind() function is not immediately called. The bind() function returns a function and this binds well. Let's take an example to help understand bind() the application scenario of a function:

var small = { A: 1, go: function (b,c,d) { Console.log (this.a+b+c+d); }}var large = { a: +}

Perform:

Small.go (2, 3, 4); //Output ten

What if we want to use large.a the value instead small.a ? We can use call/apply :

Small.go.call (large, 2, 3, 4); //Output 109

But what if we don't know what value the three parameters should pass in now? We can use bind :

var bindtest = Small.go.bind (large, 2);

If we're going to bindTest print it out under the console, we'll see:

Console.log (bindtest); //Output function (b,c,d) {console.log (this.a+b+c+d);}

Note: The function is already this bound to the large object, and the first parameter is passed in b . So, the next thing we need to do is pass in the remaining parameters:

Bindtest (3, 4); //Output 109

Arrow function (= =)

Because it takes a lot of space, we will write a blog to introduce it.

Conclusion

When you finish reading this blog, you should be able to understand the objects that are pointed to in most cases this .
Let's take a look at the following:

    1. thisis usually determined by the execution environment of the current function;
    2. In global scope, this point to Global Object ( window object);
    3. When using new keyword declaration, this point to new object;
    4. We can use call() , bind() to apply() set this ;
    5. The arrow function is not bound this .

Welcome to join our Fundebug full stack bug Monitor Exchange Group: 622902485.


Copyright NOTICE: Please specify the author fundebug and this address:https://blog.fundebug.com/2017/05/17/javascript-this-for-beginners/

JavaScript beginners MUST See "this"

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.