Skip to content

Comment on Stop Using Constructors in JS (2012)parent

Comments

The pattern didn't break subclassing there, your code did by not continuing the pattern and then not using new :)

Personally, I only use this pattern for cases where it's more convenient not to have to use new (e.g. building declarative APIs for defining things) and let 'use strict'; catch the rest.

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.

I'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

If that's Backbone's extend, that can be fixed:

http://bl.ocks.org/insin/raw/db5f79d7d97ee6200245/

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.