Using “Object.create” instead of “new”

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

    You could make the init method return this, and then chain the calls together, like this:

    var userB = {
        init: function(nameParam) {
            this.id = MY_GLOBAL.nextId();
            this.name = nameParam;
            return this;
        },
        sayHello: function() {
            console.log('Hello '+ this.name);
        }
    };
    
    var bob = Object.create(userB).init('Bob');
    

提交回复
热议问题