gpt4 book ai didi

javascript - Object.create 工作 new() 不

转载 作者:行者123 更新时间:2023-11-30 10:03:01 26 4
gpt4 key购买 nike

有这个:

sillyObject = {
init: function init(sillySettings) {
name = sillySettings.name
}
};

sillyObject.showAlert = function(x) {
return alert(x);
};

当我运行这段代码时:

var sillyvar  = new sillyObject()
sillyvar.init(mySettings);
silly.showAlert("silly!");

我得到一个错误,但是如果我使用 Object.create 运行相同的东西,它就会运行..

var sillyvar  = Object.create(sillyObject);
sillyvar.init(mySettings);
silly.showAlert("silly!");

任何(愚蠢的)帮助将不胜感激。

最佳答案

new 和 Object.create 是两个根本不同的东西。

new 将期望后面跟一个函数,如果不是(如您所见),它将给您一个错误。这是因为 new 期望调用构造函数,然后将其用作新执行上下文的基础。在该上下文中,函数将 this 绑定(bind)到执行上下文的范围。一旦函数完成执行,它返回 this 值,该值通常附加了一些数据。在您的示例中,它看起来像这样:

function sillyObject() {}
sillyObject.prototype.init = function(sillySettings) {
//perhaps you wanted to attach this name to the sillyObject?
name = sillySettings.name;
//which would look like this
this.name = sillySettings.name;
//because `this` here refers to the object context (remember?)
};
sillyObject.prototype.showAlert = function(x){
return alert(x);//returning alert simply returns undefined (not sure why this is used here)
};

然后您可以使用 new,它会使用构造函数创建执行上下文,然后附加原型(prototype),您最终会得到一个新的 sillyObject 实例(所有实例都会不同)。

var sO = new sillyObject();
sO.init(mySettings);
sO.showAlert("silly!");
另一方面,

Object.create() 期望一个对象作为参数(这就是您的版本在这里工作的原因)。它将基本上使用该对象参数作为模板创建一个新对象。或者作为 MDN explains it “Object.create() 方法使用指定的原型(prototype)对象和属性创建一个新对象”。如果没有对对象执行任何其他操作,这基本上会创建一个副本,这就是为什么警报在这里有效但在 new 版本中无效的原因。

关于javascript - Object.create 工作 new() 不,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30607728/

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