在此定义的方法与在类主体中定义的方法的差异

问题描述

当我通过构造函数向构造函数中的类的所有实例添加方法时,有什么区别

this.bar = function() {}

与在类主体中定义功能相反

baz() {}

class Foo {
  constructor() {
    this.bar = function() {};
  }
  
  baz() {}
}

console.log(Object.prototype.hasOwnProperty.call(new Foo,'bar')); // true
console.log(Object.prototype.hasOwnProperty.call(new Foo,'baz')); // false

如果我只是在构造函数中将this.baz替换为this.baz,则两个测试都将返回true

class Foo {
  constructor() {
    this.bar = function() {};
    this.baz = this.baz;
  }
  
  baz() {}
}

console.log(Object.prototype.hasOwnProperty.call(new Foo,'baz')); // true Now

解决方法

在构造函数中执行this.bar = function() { };时,您将为每个实例创建一个新函数,并将其分配给bar属性。如果需要的话,这可以让函数关闭构造函数中的某些内容。 (如果使用了箭头功能,该功能将在thissuper上关闭。)

当您在class中声明一个方法时,您将在该类将分配给实例的原型对象上创建一个函数,然后重新使用该函数。这样,如果该函数需要访问超类功能,则可以使用super

两者的位置都取决于您在做什么。您可以在这里看到这种差异:

class Foo1 {
    constructor() {
        this.bar = function() {};
    }
}

class Foo2 {
    bar() {}
}

const f1a = new Foo1();
const f1b = new Foo1();
console.log(f1a.bar === f1b.bar); // false

const f2a = new Foo2();
const f2b = new Foo2();
console.log(f2a.bar === f2b.bar); // true

关于此:

this.baz = this.baz;

class Foo {
  constructor() {
    this.bar = function() {};
//             vvvvvvvv−−−−−−−−−−−−−−− reads from the prototype
    this.baz = this.baz;
//  ^^^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−− writes to the instance

  }
  
  baz() {}
}

是在原型上查找功能,然后直接在对象上分配它,这就是为什么在分配之后它成为自己的属性。