this object in JS

The this keyword is only related to the execution environment of the function, not the declaration environment. What this represents is not known until the function runs. Although it changes depending on the environment, it always represents the object that called the current function.

1. Method invocation mode

When a function is saved as a property of an object, it can be called a method of that object. When a method is called, this is bound to the object.

var name = 'wang';
var obj = {
    name:'xuan',
    sayName:function(){
        var name = 'abiu';
        console.log(this.name);
    }
}
obj.sayName();//xuan

The sayName function is called as a method of the object obj, so this in the function body represents the obj object.

2. Function call mode

When a function is not a property of an object, it is called as a function. In this mode, this is bound to the global object, which in the browser environment is the window object.

var name = "wang";
function sayName() {
    var name='xuan';
    console.log(this.name);
}
sayName();//wang

sayName is called in function call mode, so this points to the window object

3. Constructor mode

If a function is called with the new keyword in front of it, a new object is created that is connected to the prototype member of the function, and this is also bound to the new object. In this case, the function can be the constructor of this object.

function Person(){
    this.name='wang';
}
var person = new Person ();
console.log(person.name);//wang

Person is called as a constructor, and this inside the function body is bound to the newly created object person

Four, apply call mode

In js, functions are also objects. All function objects have two methods: apply and call. These two methods allow us to construct a parameter value and pass it to the calling function, and also allow us to modify the value of this. The value of this is passed to the calling function. The first parameter entered, if no parameter is passed in, this represents window.

var name = 'wang';
var person = {
    name:'wang in person';
}
function sayName(){
    console.log(this.name);
}
sayName();//wang
sayName.apply(person);//wang in person
sayName.apply();//wang

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325818942&siteId=291194637