0

When I add a normal function to the prototype, 'this' pointing is right,but when i use arrow function,the 'this' pointing is messive ,just like below picture

enter image description here

what is the 'this' pointing in the prototype function when i use arrow function?

function Person(name, age, address) {
    this.name = name;
    this.age = age;
    this.address = address;
    if (typeof Person._initialized === 'undefined') {
        Person.prototype.getName = function() {
            console.log(this);
        };
        Person._initialized = true;
    }
}
let person1 = new Person('12', 11, '123');
let person2 = new Person('122', 11, '1223');
person1.getName();
person2.getName();


function Person2(name, age, address) {
    this.name = name;
    this.age = age;
    this.address = address;
    if (typeof person2._initialized === 'undefined') {
        Person2.prototype.getName = ()=> {
            console.log(this);
        };
        Person2._initialized = true;
    }
}
let person11 = new Person2('12', 11, '123');
let person22 = new Person2('122', 11, '1223');
person11.getName();
person22.getName();
blue xx
  • 1
  • 2
  • Hi, Welcome. Please feel free to paste your code in question. – bhansa Aug 23 '22 at 04:40
  • https://www.codementor.io/@dariogarciamoya/understanding-this-in-javascript-with-arrow-functions-gcpjwfyuc – bhansa Aug 23 '22 at 04:41
  • 1
    @DecPK perhaps add this to the dupe list? https://stackoverflow.com/questions/28371982/what-does-this-refer-to-in-arrow-functions-in-es6 – Nick Aug 23 '22 at 04:44
  • I know the scope of the arrow function is its parent scope,But in the above code, shouldn't the scope point to the new object created – blue xx Aug 23 '22 at 04:54

0 Answers0