This in javascript

  • 2020-03-30 04:33:56
  • OfStack

This object has always been a pain in the ass in js, and it's hard to tell exactly what it's pointing to, and we often make This kind of mistake because of our experience with C++ or python self. Let's go into the details of where this object belongs.

Rule1: this for the global environment

The environment of javascript is naturally determined by functions. In js, the context cannot be separated by code blocks. The environment that is not wrapped by functions is the global environment


var name='jjj';
console.log(this.name);
//Will successfully output JJJ

Rule2: this when called as a method

This is obviously a good case to judge, and it's consistent with self in python, this definitely points to the object that calls the method


var user={
    name:'kkk'
};
user.getName=function(){
    console.log(this.name);
};
user.getName();
//It will output KKK

Rule3: this as a constructor

I don't have to tell you this, but it's clearly pointing to a newly created object, and the constructor doesn't actually create the object, it just initializes it, and the object is created before it runs
Here's an example


function User(name){
    this.name=name;
}
var f1=new User('kkk');
var f2=User('kkk');
console.log(f1.name);//kkk
console.log(f2.name);//Undefined has no name

Rule4: this in an indirect call

An indirect call is a function called with apply and call, where this refers to the first parameter in their argument list.


var setName=function(name){
    this.name=name;
};
var user={level:2};
user.apply(setName,'jjj');
console.log(user.name);//jjj

Rule5: this in other cases

Remember that in other cases this will not be changed, and this is where the most mistakes are made.


var name = "clever coder";
var person = {
    name : "foocoder",
    hello : function(sth){
        var sayhello = function(sth) {
            console.log(this.name + " says " + sth);
        };
        sayhello(sth);
    }
}
person.hello("hello world");//clever coder says hello world

The code above looks strange. Shouldn't this point to a person?
We should remember that the this in the nested function does not refer to the nested function, in this case the this in sayhello does not refer to the function corresponding to hello. If we change the example a little bit to


hello:function(sth){
    console.log(this.name + " says " + sth);
}
//foocoder says hello world

As you can see, sayhello is not being called as a method at this point, so this points to the global object...
Now the problem is, running the original example with node will show you undefined says hello world, I don't know if there's a god to explain.

Rule6 :eval breaks all rules

I'll end with an example


var name = "clever coder";
var user={
    name:'kkk'
};
user.getName=function(){
    console.log(this.name);
};
var get=user.getName;
get();//clever coder

Does that make sense?


Related articles: