Using “Object.create” instead of “new”

后端 未结 15 2126
隐瞒了意图╮
隐瞒了意图╮ 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.
    0 讨论(0)
  • 2020-11-22 07:11

    While Douglas Crockford used to be a zealous advocate of Object.create() and he is basically the reason why this construct actually is in javascript, he no longer has this opinion.

    He stopped using Object.create, because he stopped using this keyword altogether as it causes too much trouble. For example, if you are not careful it can easily point to the global object, which can have really bad consequences. And he claims that without using this Object.create does not make sense anymore.

    You can check this video from 2014 where he talks at Nordic.js:

    https://www.youtube.com/watch?v=PSGEjv3Tqo0

    0 讨论(0)
  • 2020-11-22 07:13

    You have to make a custom Object.create() function. One that addresses Crockfords concerns and also calls your init function.

    This will work:

    var userBPrototype = {
        init: function(nameParam) {
            this.name = nameParam;
        },
        sayHello: function() {
            console.log('Hello '+ this.name);
        }
    };
    
    
    function UserB(name) {
        function F() {};
        F.prototype = userBPrototype;
        var f = new F;
        f.init(name);
        return f;
    }
    
    var bob = UserB('bob');
    bob.sayHello();
    

    Here UserB is like Object.create, but adjusted for our needs.

    If you want, you can also call:

    var bob = new UserB('bob');
    
    0 讨论(0)
提交回复
热议问题