gpt4 book ai didi

javascript - 使用 "Object.create"而不是 "new"

转载 作者:IT老高 更新时间:2023-10-28 11:03:26 25 4
gpt4 key购买 nike

Javascript 1.9.3/ECMAScript 5 引入了 Object.create,其中 Douglas Crockford 一直是 advocating需很长时间。如何将下面代码中的 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'?

最佳答案

只有一层继承,您的示例可能无法让您看到 Object.create 的真正好处。 .

这种方法可以让你轻松实现差分继承,其中对象可以直接从其他对象继承。

在您的 userB 示例中,如果您在现有对象实例上再次调用此方法,我认为您的 init 方法不应该是公共(public)的甚至不存在, idname 属性将会改变。

Object.create 允许您使用其第二个参数初始化对象属性,例如:

var userB = {
sayHello: function() {
console.log('Hello '+ this.name);
}
};

var bob = Object.create(userB, {
'id' : {
value: MY_GLOBAL.nextId(),
enumerable:true // writable:false, configurable(deletable):false by default
},
'name': {
value: 'Bob',
enumerable: true
}
});

如您所见,属性可以在 Object.create 的第二个参数上初始化,对象字面量使用的语法类似于 Object.definePropertiesObject.defineProperty 方法。

它可以让您设置属性属性(enumerablewritableconfigurable),非常有用。

关于javascript - 使用 "Object.create"而不是 "new",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2709612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com