3 ms·
You should never be using `.constructor` anyway because it isn't reliable because a very common pattern replaces the `.prototype` with a new object who's `.cons
by hajile 9y ago
You should never be using `.constructor` anyway because it isn't reliable because a very common pattern replaces the `.prototype` with a new object who's `.constructor` is `Object`
var Foo = function () {};
Foo.prototype = {
bar() { return 'bar'; }
};
var f = new Foo();
f.constructor === Object;
When you use `class` you are still messing with `.prototype`. The danger is that programmers new to JS don't understand that they are and don't understand why that matters.
Calling `super` is very anti-pattern in JS. Unlike classic OOP, parents are not static. Lots of very common things can rip that rug out from under you by modifying the parent in many different ways (createProperty, Symbols, proxies/reflection, etc).
Static methods do indeed exist without classes.
class Foo {
static bar() { return 'bar'; }
}
//is identical to
function Foo() {}
Foo.bar = function() { return 'bar'; }
If you use `Object.create()` and ES6 object literal syntax you don't have to type `function` either. You get the added bonus of being easily able to wrap it in a normal function that avoids constructor weirdness
var someProto = {
bar() { return 'bar'; }
}
var myInst = Object.create(someProto);
- geoelectric 9y agoTo be absolutely fair, the pattern at the top is buggy in that you're supposed to also set Foo.prototype.constructor = Foo; ...after replacing the prototype object that way. MDN (for example) covers this in a few pages, including: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Ob... That said, it's a pretty common bug, particularly with stuff like: Foo.prototype = Object.create(FooParent.prototype) // Crockford-style inheritance console.log(Foo.prototype.constructor.name) // "FooParent"