此处定义的方法与 class 正文中定义的方法不同
Difference of methods defined on this in contrast to defined in class body
当我通过
向构造函数中的class的所有实例添加方法时有什么区别
this.bar = function() {}
相对于在 class 正文中定义函数
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
,则两个测试 return true
:
class Foo {
constructor() {
this.bar = function() {};
this.baz = this.baz;
}
baz() {}
}
console.log(Object.prototype.hasOwnProperty.call(new Foo, 'bar')); // true
console.log(Object.prototype.hasOwnProperty.call(new Foo, 'baz')); // true now
当您在构造函数中执行 this.bar = function() { };
时,您正在为每个实例创建一个新函数,并将其分配给 bar
属性。这允许函数 关闭 构造函数中的某些内容(如果需要的话)。 (如果您使用箭头函数,该函数将关闭 this
和 super
。)
当您在 class
中声明一个方法时,您是在 class 将分配给实例的原型对象上创建一个函数,并重用该函数。这让函数在需要访问超级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() {}
}
那就是在原型上查找函数,然后直接在对象上赋值,所以赋值后就变成了自己的属性。
当我通过
向构造函数中的class的所有实例添加方法时有什么区别this.bar = function() {}
相对于在 class 正文中定义函数
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
,则两个测试 return true
:
class Foo {
constructor() {
this.bar = function() {};
this.baz = this.baz;
}
baz() {}
}
console.log(Object.prototype.hasOwnProperty.call(new Foo, 'bar')); // true
console.log(Object.prototype.hasOwnProperty.call(new Foo, 'baz')); // true now
当您在构造函数中执行 this.bar = function() { };
时,您正在为每个实例创建一个新函数,并将其分配给 bar
属性。这允许函数 关闭 构造函数中的某些内容(如果需要的话)。 (如果您使用箭头函数,该函数将关闭 this
和 super
。)
当您在 class
中声明一个方法时,您是在 class 将分配给实例的原型对象上创建一个函数,并重用该函数。这让函数在需要访问超级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() {}
}
那就是在原型上查找函数,然后直接在对象上赋值,所以赋值后就变成了自己的属性。