In the following code,
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') }
becomes a property of newly created instance i.e.
p1.hasOwnProperty('read')
is true
as opposed to speak() { console.log('I am speaking'); }
gets assigned to PersonClass.prototype
. i.e.
p1.hasOwnProperty('speak')
is False
p1.__proto__.hasOwnProperty('speak')
is true
Can somebody pls explain why this happens.
Essentially what's the diff between two way of method declarations inside class.
I thought speak() {...}
was just shorter syntax for speak = function() {...}
(in ES6)
Thanks