Using “Object.create” instead of “new”

后端 未结 15 2343
隐瞒了意图╮
隐瞒了意图╮ 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: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');
    

提交回复
热议问题