Using “Object.create” instead of “new”

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

    With only one level of inheritance, your example may not let you see the real benefits of Object.create.

    This methods allows you to easily implement differential inheritance, where objects can directly inherit from other objects.

    On your userB example, I don't think that your init method should be public or even exist, if you call again this method on an existing object instance, the id and name properties will change.

    Object.create lets you initialize object properties using its second argument, e.g.:

    var userB = {
      sayHello: function() {
        console.log('Hello '+ this.name);
      }
    };
    
    var bob = Object.create(userB, {
      'id' : {
        value: MY_GLOBAL.nextId(),
        enumerable:true // writable:false, configurable(deletable):false by default
      },
      'name': {
        value: 'Bob',
        enumerable: true
      }
    });
    

    As you can see, the properties can be initialized on the second argument of Object.create, with an object literal using a syntax similar to the used by the Object.defineProperties and Object.defineProperty methods.

    It lets you set the property attributes (enumerable, writable, or configurable), which can be really useful.

提交回复
热议问题