gpt4 book ai didi

javascript - Object.create 说明

转载 作者:行者123 更新时间:2023-11-30 18:19:59 24 4
gpt4 key购买 nike

我对以下规范的 object.create 方法有疑问:

Object.create = function(o, props) {
function F() {}
F.prototype = o;

if (typeof(props) === "object") {
for (prop in props) {
if (props.hasOwnProperty((prop))) {
F[prop] = props[prop];
}
}
}
return new F();
};

在上面代码的第 3 行,我们将 F 对象的原型(prototype)属性设置为 o 参数的原型(prototype)。

我本以为这意味着 o 和 F 都指向同一个原型(prototype),因此指向同一组成员。

但是代码随后继续复制 prop in props 循环中的所有成员。

如果我们继续手动复制所有成员,那么在第 3 行设置原型(prototype)有什么意义?

最佳答案

您的问题中 Object.create 的版本存在错误:循环将属性附加到构造函数 F(不是返回的对象,或其原型(prototype)),这意味着它们在创建的对象中不可访问。

Object.create 的第二个参数的属性应该被复制到新创建的对象中。 Mozilla documentation for Object.create像这样说:

If specified and not undefined, an object whose enumerable own properties (that is, those properties defined upon itself and not enumerable properties along its prototype chain) specify property descriptors to be added to the newly-created object, with the corresponding property names.

尝试使用问题中的 Object.create 版本运行以下代码:

o = Object.create(
{a: "prototype's a", b: "prototype's b"},
{a: "object's a"}
);

你会发现 o.a == "prototype's a"o.b == "prototype's b", "object's a" 是迷路了。

函数的以下版本可能更有用:

Object.create = function(o, props) {
var newObj;

// Create a constructor function, using o as the prototype
function F() {}
F.prototype = o;

// Create a new object using F as the constructor function
newObj = new F();

// Attach the properties of props to the new object
if (typeof(props) === "object") {
for (prop in props) {
if (props.hasOwnProperty((prop))) {
newObj[prop] = props[prop];
}
}
}

return newObj;
};

让我们用同样的例子试试看:

o = Object.create(
{a: "prototype's a", b: "prototype's b"},
{a: "object's a"}
);

新对象 o 是使用具有属性 ab 的原型(prototype)创建的,它有自己的属性 a.

我们先看o.b:o.hasOwnProperty("b")会返回false,因为o 没有名为 b 的属性。这就是原型(prototype)出现的地方;因为没有属性 b 它是在原型(prototype)上查找的,因此 o.b === "prototype's b"

另一方面,o.hasOwnProperty("a") 将返回 true,因为 o 确实有一个 a 属性。 o.a == "object's a" 并且没有从原型(prototype)中查找任何内容。

正如 @chuckj's answer 中指出的那样, Object.create 的正确实现比这更复杂。有关详细信息,请参阅 John Resig's post on ECMAScript 5 Objects and Properties .

关于javascript - Object.create 说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12295729/

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