【发布时间】:2019-12-04 22:27:54
【问题描述】:
在下面的代码中,
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 中)
谢谢
【问题讨论】:
-
因为js遵循原型继承。
-
不,方法语法不是类属性的缩写。
-
类主体中的
variableName = ...语法等同于constructor中的this.variableName = ...语句。
标签: javascript es6-class function-expression class-fields