使用"Object.create"而不是"new"
- 论坛
- 使用"Object.create"而不是"new"
13 浏览
使用"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'?