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”?
Object.create
来获得与new UserA('bob')
相同的单步功能。 - Rick Jollynew
从未得到广泛采纳。 - Andy