Javascript 1.9.3 / ECMAScript 5 introduces Object.create
, which Douglas Crockford amongst others has been advocating for a long time.(Javascript 1.9.3 / ECMAScript 5引入了Object.create
,这是Douglas Crockford等人提倡的很长时间了。)
How do I replace new
in the code below with Object.create
?(如何使用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();
(Assume MY_GLOBAL.nextId
exists).((假设存在MY_GLOBAL.nextId
)。)
The best I can come up with is:(我能想到的最好的是:)
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();
There doesn't seem to be any advantage, so I think I'm not getting it.(似乎没有任何优势,所以我想我没有。) I'm probably being too neo-classical.(我可能太新古典了。) How should I use Object.create
to create user 'bob'?(我应该如何使用Object.create
创建用户“ bob”?)
ask by Graham King translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…