在下面的代码中,
class PersonClass {
constructor(fname) {
this.fname = fname;
}
read = function() { console.log('I am reading') }
speak () { console.log('I am speaking'); }
}
//Instantiate
let p1 = new PersonClass('Raj')
read = function() { console.log('I am reading') }
成为新创建实例的属性,即
p1.hasOwnProperty('read')
为 true
相对于 speak() { console.log('I am speaking'); }
被分配给 PersonClass.prototype
。即
p1.hasOwnProperty('speak')
为 False
p1.__proto__.hasOwnProperty('speak')
为 true
有人能解释一下为什么会这样吗?
本质上,类中两种方法声明方式之间的区别是什么。
我认为 speak() {...}
只是 speak = function() {...}
(在 ES6 中)的较短语法
谢谢
read = function() { console.log('I am reading') }
是新的类字段 语法。它实际上与在构造函数中分配给实例的 read
属性相同:
class PersonClass {
constructor(fname) {
this.read = function() {
console.log('I am reading')
}
this.fname = fname;
}
speak() {
console.log('I am speaking');
}
}
speak
,另一方面,是一个普通的类方法,也就是说它在原型(prototype)上,PersonClass.prototype
,和是一回事Object.getPrototypeOf(p1)
,与 p1.__proto__
相同(已弃用语法)。
class PersonClass {
constructor(fname) {
this.read = function() {
console.log('I am reading')
}
this.fname = fname;
}
speak() {
console.log('I am speaking');
}
}
let p1 = new PersonClass('Raj')
console.log(
PersonClass.prototype.hasOwnProperty('speak'),
Object.getPrototypeOf(p1) === PersonClass.prototype,
p1.__proto__ === PersonClass.prototype
);
因此,speak
属性位于实例的内部原型(prototype) 上,而不是实例本身。 read
属性是实例的直接属性,就像 fname
属性一样。
请记住,类字段语法是 still an experimental proposal (第 3 阶段)。它至少在 Chrome 中实现了,但还不是完全正式的。