The problem of this in javascript

 function People(name) {
            this.name = name;
            this.sayName = function () {
                console.log("my name is:" + this.name);
            }
        }
        People.prototype.walk = function () {
            console.log(this.name + " is walking"); this
        }
        var p1 = new People("");
        var p2 = new People("");

People.prototype.walk () Sorry, the problem is not fully described, so what does the this in this function represent

Mar.10,2021
The direction of

this can only be determined when it is called, so you cannot determine the place where you add comments, or it conforms to those pointing methods. You can refer to how to call walk,. You can search for the relationship between this calling method and this pointing. You can search for this pointing .


print it out

People.prototype.walk = function ()
{
    console.log(this);
}

https://www.cnblogs.com/pssp/., you can take a look at


function People(name) {
    this.name = name;
    this.sayName = function () {
        console.log('my name is:' + this.name);
    }
}
People.prototype.walk = function () {
    console.log(this.name + ' is walking'); 
}
var p1 = new People('');
p1.sayName()
p1.walk();

/ / my name is: We
/ / We is walking

1. Ordinary function this pointing to problem: sayName () can be understood as closure, internal function can access external variables, this pointing to external name
2,: walk () function pointing to problem based on prototype chain this is based on inheritance of people prototype chain line. Walk () inherits all the attributes of the parent class, so the this here still points to the name
3 of the parent class. The pointing problem based on the arrow function this: this points to the upper level of the arrow function
Summary: the pointing of this is very complex, and the specific directivity problem should be considered according to the method in which the function is called. You do not know the javascript has a specific understanding of the direction and scope of this, I hope it will be helpful to you

Menu