Benefits of using `Object.create` for inheritance

前端 未结 4 1251
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 05:43

I\'ve been trying to wrap my head around the new Object.create method which was introduced in ECMAScript 5.

Usually when I want to use inheritance I do

4条回答
  •  梦如初夏
    2020-11-21 06:14

    I'm trying to illustrate the difference a little bit:

    Here is what basically happens when you write new Animal():

        //creating a new object
        var res = {};
    
        //setting the internal [[prototype]] property to the prototype of Animal
        if (typeof Animal.prototype === "object" && Animal.prototype !== null) {
            res.__proto__ = Animal.prototype;
        }
    
        //calling Animal with the new created object as this
        var ret = Animal.apply(res, arguments);
    
        //returning the result of the Animal call if it is an object
        if (typeof ret === "object" && ret !== null) {
            return ret;
        }
    
        //otherise return the new created object
        return res;
    

    And here is what basically happens with Object.create:

        //creating a new object
        var res = {};
    
        //setting the internal [[prototype]] property to the prototype of Animal
        if (typeof Animal.prototype !== "object") {
            throw "....";
        }
        res.__proto__ = Animal.prototype;
    
        //return the new created object
        return res;
    

    So it does the same but it doesn't call the Animal function and it also always returns the new created object. In your case you end up with two different objects. With the first method you get:

    Dog.prototype = {
        name: undefined,
        __proto__: Animal.prototype
    };
    

    and with the second method you get:

    Dog.prototype = {
        __proto__: Animal.prototype
    };
    

    You don't really need to have the name property in your prototype, because you already assigning it to your Dog instance with Animal.call(this, 'Dog');.

    Your primary goal is to let your Dog instance access all the properties of the Animal prototype, which is achieved by both methods. The first method however does some extra stuff that is not really needed in your case or can even cause unwanted results as Pumbaa80 mentioned.

提交回复
热议问题