function Bar() {
Foo.call(this);
}
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.constructor = Bar;
Foo.prototype.thing = function() { ....
What other "approach" to prototypical inheritance is there in JavaScript? The module pattern doesn't use prototypes.It would be great to know what the benefits are vs declaring function literals on an object, or declaring a function directly on Bar's prototype.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inhe...
class Foo { constructor() { this.whatever = 4; }
bar() {
this.whatever = 3;
}
}var foo = new Foo();
blah.onSomeEvent(foo.bar);
// When SomeEvent is triggered on blah, `this` will refer to blah, not foo.
console.log(blah.whatever); // 3 console.log(foo.whatever); // 4
// You have to: blah.onSomeEvent(foo.bar.bind(foo));
console.log(blah.whatever); // undefined console.log(foo.whatever); // 3
Which I know is just traditional JS, but it's a little unexpected because that's not how most OO languages operate.
- Harder to screw up. Even if you know what you're doing, prototypical inheritance involves several steps which can get repetitive.
- Interoperable with non-es6 "classes". It's not like you're losing anything.
function super(obj, method) {
for (var p = obj.prototype; p; p = p.prototype)
if (p[method])
return p[method];
throw method+" not found";
}
then use: subclass.prototype.overridden = function(x,y) {
super(this, 'some_overriden_method').call(this, x, y);
// ...
}
If so, that means it's just sugar. If not, what does it do differently?ES6's class system is infinitely better.