使用"Object.create"而不是"new"

13 浏览
0 Comments

使用"Object.create"而不是"new"

Javascript 1.9.3 / ECMAScript 5引入了Object.create,这是Douglas Crockford等人长期以来一直提倡的。我如何用Object.create来替换下面代码中的new关键字?

var UserA = function(nameParam) {
    this.id = MY_GLOBAL.nextId();
    this.name = nameParam;
}
UserA.prototype.sayHello = function() {
    console.log('Hello '+ this.name);
}
var bob = new UserA('bob');
bob.sayHello();

(假设MY_GLOBAL.nextId存在)。

我能想到的最好的方法是:

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

看起来没有什么优势,所以我觉得我没有理解。我可能太过于新古典主义了。我应该如何使用Object.create来创建用户'bob'?

0