Using “Object.create” instead of “new”

后端 未结 15 2461
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 06:08

Javascript 1.9.3 / ECMAScript 5 introduces Object.create, which Douglas Crockford amongst others has been advocating for a long time. How do I replace new

15条回答
  •  忘掉有多难
    2020-11-22 06:50

    There is really no advantage in using Object.create(...) over new object.

    Those advocating this method generally state rather ambiguous advantages: "scalability", or "more natural to JavaScript" etc.

    However, I have yet to see a concrete example that shows that Object.create has any advantages over using new. On the contrary there are known problems with it. Sam Elsamman describes what happens when there are nested objects and Object.create(...) is used:

    var Animal = {
        traits: {},
    }
    var lion = Object.create(Animal);
    lion.traits.legs = 4;
    var bird = Object.create(Animal);
    bird.traits.legs = 2;
    alert(lion.traits.legs) // shows 2!!!
    

    This occurs because Object.create(...) advocates a practice where data is used to create new objects; here the Animal datum becomes part of the prototype of lion and bird, and causes problems as it is shared. When using new the prototypal inheritance is explicit:

    function Animal() {
        this.traits = {};
    }
    
    function Lion() { }
    Lion.prototype = new Animal();
    function Bird() { }
    Bird.prototype = new Animal();
    
    var lion = new Lion();
    lion.traits.legs = 4;
    var bird = new Bird();
    bird.traits.legs = 2;
    alert(lion.traits.legs) // now shows 4
    

    Regarding, the optional property attributes that are passed into Object.create(...), these can be added using Object.defineProperties(...).

提交回复
热议问题