What is the difference between when I add a method to all instances of a class in the constructor via
this.bar = function() {}
as opposed to defining the function right in the class body
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
If I simply replace this.baz with this.baz in the constructor, both tests 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