Home >Web Front-end >JS Tutorial >Let's talk about 'this” in JavaScript

Let's talk about 'this” in JavaScript

伊谢尔伦
伊谢尔伦Original
2016-12-05 10:01:53956browse

In addition to closures, there is another concept that is difficult to understand in JS that should bear the brunt: this. This thing is often confused by people, so today we will take a closer look at its true appearance.

Define an object:

var Charles = {
    living: true,
    age:23,
    gender:male,
    getGender:function(){ return Charles.gender;
    }
}; console.log(Charles.getGender()); //输出:male

The following code has the same effect:

var Charles = {
    living: true,
    age:23,
    gender:male,
    getGender:function(){ return this.gender; //注意“this” }
}; console.log(Charles.getGender()); //输出:male

So, what does this refer to in the code? How should we analyze it, because sometimes it is difficult to distinguish the true identity of this in a specific environment. So, now, you need to remember one sentence:
When the host function of this value is encapsulated in another function, or called in the context of another function, this value is always for the global (head/window) object Quote.
In other words, the this value is inside the nested function and always points to window for ES5.

var myObject = {
    myProperty: 'I can see the light',
    myMethod: function(){ var that = this; console.log(this); 
    //输出:'Object(这里是myObject)' var helperFunction = function(){ console.log(that.myProperty); 
    // 输出'I can see the light' console.log(this); //如果不使用`that`,则输出'window',因为是在嵌套函数里面 }(); //立即执行 }
}
myObject.myMethod(); //调用 myMethod

Combined with the above sentence, for ES5, this is the situation:

var myObject = {
    func1: function(){ console.log(this); //输出 'Object'(第一层函数) var func2= function(){ console.log(this); 
    //从此处开始,this都是window(第二层函数) var func3= function(){ console.log(this); //当然是window }();
        }();
    }
}
myObject.func1();

Lets talk about this” in JavaScript

As shown in the picture

At this point, you should understand the position of this in JS, and I believe it will not be divided again in the future Not sure anymore.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn