Javascript 1.9.3/ECMAScript 5介绍Object.create道格拉斯·克罗克福德等人长期以来一直在倡导.如何new在下面的代码中替换Object.create?
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();
Run Code Online (Sandbox Code Playgroud)
(假设存在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();
Run Code Online (Sandbox Code Playgroud)
似乎没有任何优势,所以我想我没有得到它.我可能过于新古典主义了.我应该如何使用MY_GLOBAL.nextId创建用户'bob'?