JavaScript Inheritance with Prototypes — 'constructor' property?

前端 未结 4 1899
孤城傲影
孤城傲影 2020-12-25 13:40

I\'ve seen a lot of stuff like this, and am looking for the proper solution to basic JavaScript inheritance:

function Food(){}  // Food  constructor (class)
         


        
4条回答
  •  鱼传尺愫
    2020-12-25 14:44

    What you are doing wrong is to reuse the basicFood object for multiple child 'classes'. Instead, new up a new one. That way, as you add members to the prototype (new instance of the parent), you're adding it to an instance that is not shared among other inheriting classes.

    Now, there's one thing that your code is lacking, and that is constructors without side effects. Many constructors requires arguments, and will throw without them - but how can you construct a prototype for a new descending class without new'ing up a parent? Well, we're not actually interested in the parent function, only in the parents prototype. So what you can do is

    function Parent() { /*some side effect or invariant */ }
    Parent.prototype.foo = ...
    function Child() { Parent.call(this); }
    
    // the next few lines typically go into a utility function
    function F() {} // a throw-away constructor
    F.prototype = Parent.prototype; // borrow the real parent prototype
    F.prototype.constructor = Parent; // yep, we're faking it
    Child.prototype = new F(); // no side effects, but we have a valid prototype chain
    Child.prototype.bar = ... // now continue adding to the new prototype
    

提交回复
热议问题