使用“Object.create”而不是“New”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();(假设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’?
3 回答
慕少森
TA贡献2019条经验 获得超9个赞
Object.create(...)
new object
.
Object.create
new
Object.create(...)
var Animal = { traits: {},}var lion = Object.create(Animal);lion.traits.legs = 4;var bird = Object.create(Animal);bird.traits.legs = 2;alert(lion.traits.legs) // shows 2!!!
Object.create(...)
Animal
lion
bird
function Animal() { this.traits = {};}function Lion() { }Lion.prototype = new Animal();function Bird() { }Bird.prototype = new Animal();var lion = new Lion();lion.traits.legs = 4;var bird = new Bird();bird.traits.legs = 2;alert(lion.traits.legs) // now shows 4
Object.create(...)
Object.defineProperties(...)
.
添加回答
举报
0/150
提交
取消