3 ms·
this part here is supposed to solve the problem with people forgetting new: if (!(this instanceof User)) { return new User(name, lastname); } I
by phpnode 12y ago
this part here is supposed to solve the problem with people forgetting new:
if (!(this instanceof User)) {
return new User(name, lastname);
}
I'm pointing out that this doesn't work if you extend the class.
The point is - don't forget `new` because tricks like this will not save you, in fact this is arguably worse - you think you're getting a `Person` but you get a `User` with no immediate errors, at least if you forget `new` then you'll get an error straight away in strict mode.
- insin 12y agoIf that's Backbone's extend, that can be fixed: http://bl.ocks.org/insin/raw/db5f79d7d97ee6200245/ http://bl.ocks.org/insin/raw/db5f79d7d97ee6200245/
- rizalp 12y agoI've using Js for quite some time, and the behavior of prototype chain and instanceof always give me headache when I'm trying to do simple inheritance... For now, I'll keep using `_.create` to do Inheritance. Of course it means another library to keep using and more verbose. But whatever... var Person = function(){ User.call(this) }; Person.prototype = _.create(User.prototype, { 'constructor': Person }); var p = new Person(); p instanceof User //true p instanceof Person //true