Using “Object.create” instead of “new”

后端 未结 15 2157
隐瞒了意图╮
隐瞒了意图╮ 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:58

    Another possible usage of Object.create is to clone immutable objects in a cheap and effective way.

    var anObj = {
        a: "test",
        b: "jest"
    };
    
    var bObj = Object.create(anObj);
    
    bObj.b = "gone"; // replace an existing (by masking prototype)
    bObj.c = "brand"; // add a new to demonstrate it is actually a new obj
    
    // now bObj is {a: test, b: gone, c: brand}
    

    Notes: The above snippet creates a clone of an source object (aka not a reference, as in cObj = aObj). It benefits over the copy-properties method (see 1), in that it does not copy object member properties. Rather it creates another -destination- object with it's prototype set on the source object. Moreover when properties are modified on the dest object, they are created "on the fly", masking the prototype's (src's) properties.This constitutes a fast an effective way of cloning immutable objects.

    The caveat here is that this applies to source objects that should not be modified after creation (immutable). If the source object is modified after creation, all the clone's unmasked properties will be modified, too.

    Fiddle here(http://jsfiddle.net/y5b5q/1/) (needs Object.create capable browser).

提交回复
热议问题