Correct javascript inheritance

javascript

Solution

Simple: `Object.create` is not supported in all environments, but can be shimmed with `new`. Apart from that, the two have different aims: `Object.create` just creates a Object inheriting from some other, while `new` also invokes a constructor function. Use what is appropriate.

In your case you seem to want that `RestModel.prototype` inherits from `Model.prototype`. `Object.create` (or its shim) is the correct way then, because you do not want to a) create a new instance (instantiate a `new Model`) and b) don't want to call the Model constructor:

RestModel.prototype = Object.create(Model.prototype);

If you want to call the Model constructor on RestModels, that has nothing to do with prototypes. Use `call()` or `apply()` for that:

function RestModel() {
    Model.call(this); // apply Model's constructor on the new object
    ...
}

Problem

I've been reading a lot of articles about "inheritance" in javascript. Some of them uses `new` while others recommends `Object.Create`. The more I read, the more confused I get since it seems to exist an endless amount of variants to solve inheritance. Can someone be kind to show me the most accepted way (or defacto standard if there is one)? (I want to have an base object `Model` which I can extend `RestModel` or `LocalStorageModel`.)

Original source