js中为什么在原型链上添加方法必须是普通函数而不是箭头函数

260 阅读1分钟
因为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()); //什么也不打印