因为this指向的问题,this是js在函数调用时生成的一个内置对象,一般在运行时确定,但是箭头函数的this实在编译时就确定,箭头函数的this总指向箭头函数所在上下文的this。
function Animal(name) {
this.name = name;
}
Animal.prototype.getName = function () {
console.log(this); //当前实列对象
return this.name;
};
Animal.prototype.getNameTest = () => {
console.log(this); //window
return this.name;
};
let dog = new Animal("dog");
console.log(dog.getName()); //dog
console.log(dog.getNameTest()); //什么也不打印