在下面的代码中,
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. IE
p1.hasOwnProperty('speak')是False
p1.__proto__.hasOwnProperty('speak')是true
有人可以解释为什么会发生这种情况。
本质上,类中两种方法声明方式之间的区别是什么。
我认为speak() {...}只是更短的语法speak = function() {...}(在 ES6 中)
谢谢