Using “Object.create” instead of “new”

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

    Summary:

    • Object.create() is a Javascript function which takes 2 arguments and returns a new object.
    • The first argument is an object which will be the prototype of the newly created object
    • The second argument is an object which will be the properties of the newly created object

    Example:

    const proto = {
      talk : () => console.log('hi')
    }
    
    const props = {
      age: {
        writable: true,
        configurable: true,
        value: 26
      }
    }
    
    
    let Person = Object.create(proto, props)
    
    console.log(Person.age);
    Person.talk();

    Practical applications:

    1. The main advantage of creating an object in this manner is that the prototype can be explicitly defined. When using an object literal, or the new keyword you have no control over this (however, you can overwrite them of course).
    2. If we want to have a prototype The new keyword invokes a constructor function. With Object.create() there is no need for invoking or even declaring a constructor function.
    3. It can Basically be a helpful tool when you want create objects in a very dynamic manner. We can make an object factory function which creates objects with different prototypes depending on the arguments received.

提交回复
热议问题