Correct javascript inheritance

后端 未结 2 1997
灰色年华
灰色年华 2020-11-22 05:54

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 r

2条回答
  •  甜味超标
    2020-11-22 06:04

    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
        ...
    }
    

提交回复
热议问题