Master "this" in JS (1)

Source: Internet
Author: User

Master "this" in JS (1)

Note:Generally,functionTranslate into functions,methodTranslation as a method.

We generally say that the method of a certain object is not the function of a certain object ". The reason is that in object-oriented mode, an object is a specific amount instance and has its own method. Functions are irrelevant to objects.

In addition,scope(Scope) andcontext(Context) is also a confusing place. For more information, see Javascript Context and Scope.

Recommended reading: ES6 (1 ~ 10) Series

Writing a program in a language does not mean that the language can be correctly understood and used. Of course, the same is true for JavaScript. AlthoughJS(JavaScript for short) is a very easy-to-use language, but there are actually a lot of details in it, and beginners may not understand it. Even experienced JavaScript masters will occasionally fall into the trap.

Many experienced programmersthisHow JavaScript works is also confusing. In layman's terms,thisIt's just a referencing alias-this alias only knows the object Currently pointed to, and this is also the most tricky part.

This article clarifies your ideas and introducesthisThe internal operating principle of the keyword.

So, thisWhat is it?

In short,thisIs a special identifier Keyword -- automatically determines in each function according to the scope, pointing to the"Owner". To solve this problem completely, we need to answer two key questions:

thisHow was it created?

Each time a JavaScript function is called, a new object is created. The information includes the parameters passed in and how the function is called (invoked, where the function is called (called), and so on. This object also has an important attribute:thisThe method of the object to which the function is referenced,thisIt is automatically bound to this object.

Tip:For more information, see section 10. 4.3 of ECMAScript language specifications and related links.

var car = {  brand: Nissan,  getBrand: function(){    console.log(this.brand);  }};car.getBrand();// output: Nissan

In this examplethis.brand, This iscarObject reference. So now,this.brandEquivalentcar.brand.

thisWho points

Among all functions,thisAccording to the context (ContextThe environment in which the function is called.thisScope is not related to the location of the function definition, but depends on where the function is called (where they are called from; I. e. the context ).

Every line of JavaScript code is inExecution Context(Execution context.thisThe object to be redirected is fixed every time it enters the new execution context, and changes do not occur until it redirects to another different context. Determine the execution context (andthisYou need to find the call point (call-site). The call point is the position where the function is called in the code.

Let's take a look at the following example:

var brand = 'Nissan';var myCar = {brand: 'Honda'};var getBrand = function() {  console.log(this.brand);};myCar.getBrand = getBrand;myCar.getBrand();// output: HondagetBrand();// output: Nissan

AlthoughmyCar.getBrand()AndgetBrand()Point to the same function, butthisIs different because it depends ongetBrand()In which context to call.

We already know the method of the function object. In the function,thisBind to this object.

In the above Code, the callback function call correspondsmyCarObject, and the second response iswindow[At this timegetBrand()Equivalentwindow.getBrand()]. Therefore, different contexts produce different results.

Call Context

Next, let's take a look at different contextsthis.

Global Scope)

All JavaScript operations have unique global objects (Global object). In the browser, the global object iswindow. InNode. jsWhich isglobal.

In the context of global execution (Code other than any function ),thisIt points to a global object, whether in strict mode or not (strict mode).

Local Scope)

In the function,thisDepends on how the function is called. There are three situations:

1. Use in Simple Function Call this

The first scenario is to directly call an independent function.

function simpleCall(){  console.log(this);}simpleCall();// output: the Window object

In this case,thisThe value is not set by call. Because the code is not running in strict mode,thisIt must be an object, so its value is a global object by default.

If the value is set when the execution context is in strict mode, what is the value. If this parameter is not specifiedundefined, As shown below:

function simpleCall(){  use strict;  console.log(this);}simpleCall();// output: undefined
2. Use the Object's Method this

Save the function as the property of the object and convert it into a method. You can call this method through the object. When a function is called as an object methodthisThe value is set to the object that calls the method.

var message = {  content: I'm a JavaScript Ninja!,  showContent: function() {    console.log(this.content);  }};message.showContent();   // output: I'm a JavaScript Ninja!

showContent()YesmessageObject method.this.contentEquivalentmessage.content.

3. Use the Constructor Function this

We can usenewTo call a function. In this case, this function becomes a constructor (an object factory ). Unlike the simple function call and method call discussed earlier, the constructor calls a new objectthisAnd implicitly return the newly constructed object as the result [in short, the memory of the newly constructed object is allocated by the new operator, and the constructor only performs some initialization work ].

When a function is used as a constructornewKeyword), itsthisBind the value to the newly created object. If notnewKeyword, then it is just a common function,thisDirectwindowObject.

function Message(content){  this.content = content;  this.showContent = function(){    console.log(this.content);  };}var message = new Message(I'm JavaScript Ninja!);message.showContent();// output: I'm JavaScript Ninja!

In the above example, there isMessage()Constructor. UsenewOperator creates a brand new object namedmessage. At the same time, it is also passed to the constructor as a string for the new objectcontentAttribute. In the last line of code, we can see that the string is successfully printed, becausethisIt points to the newly created object rather than the constructor itself.

How to use it correctly this

In this section, we will learn some decisionsthisThe internal mechanism of the action.

In JavaScript, all functions are objects, so functions can have their own methods. All functions have two methods: apply () and call ().. We can use these two methods to change the context of the function, which is effective at any time and used to explicitly setthis.

apply()Method to receive two parameters: the first parameter must be setthisThe second parameter is optional. If you want to pass in the parameter, It is encapsulated as an arrayapply().

call()Method andapply()Basically the same, except that the following parameters are not arrays, they are scattered and appended one by one.

Perform the following drills:

function warrior(speed, strength){  console.log(    Warrior:  + this.kind +    , weapon:  + this.weapon +    , speed:  + speed +    , strength:  + strength  );}var warrior1 = {  kind: ninja,  weapon: shuriken};var warrior2 = {  kind: samurai,  weapon: katana};warrior.call(warrior1, 9, 5);// output: Warrior: ninja, weapon: shuriken, speed: 9, strength: 5warrior.apply(warrior2, [6, 10]);// output: Warrior: samurai, weapon: katana, speed: 6, strength: 10

Here we have a factory functionwarrior()To create different types of warrior by passing in different warrior objects ). In the factory function,thisWill point tocall()And/orapply()The input object.

In the first function call, we usecall()MethodthisSetwarrior1Object, and input other required parameters. The parameters are separated by commas. In the second function call, both functions are similar, but the input iswarrior2And encapsulate necessary parameters into an array.

Besidescall()Andapply()In addition, the bind () method is added to ECMAScript 5. You can also usebindMethod to bindthisObject. Let's take a look at the following example:

function warrior(kind){  console.log(    Warrior:  + kind +    . Favorite weapon:  + this.weapon +    . Main mission:  + this.mission  );}var attributes = {  weapon: shuriken,  mission: espionage};var ninja = warrior.bind(attributes, ninja);ninja();// output: Warrior: ninja. Favorite weapon: shuriken. Main mission: espionage

In this example,bind()The method is similar,warrior.bind()A new function (method body and scopewarrior()), And the originalwarrior()Function. The functions of the new function are the same as those of the old one.attributesObject.

bindMethod andcall,applyThe difference is that,bind()After that, the function is not executed. It can be passed to other functions and called at an appropriate time]

Summary

So, andthisThis is almost the relevant knowledge. As a beginner, mastering this is enough for you to use it correctly and have more confidence in yourself! Of course, there may also be some problems that will affect you in the Process of use. Therefore, please read the next article to learn about"this"(2 ).

 

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.