gpt4 book ai didi

javascript - Object.create 在 javascript : why does my code outputs Object instead of name string value

转载 作者:行者123 更新时间:2023-11-30 10:14:13 24 4
gpt4 key购买 nike

我测试了这段代码并使用 node.js 执行

function Person(name) {
this.name = name;
}


john = Object.create(Person);
john.name = 'John';
console.log(john.name);

它返回人。为什么它不返回“John”?

更新:我的问题不是关于 new 还是 create,我完全知道应该如何使用 new 和 create。我的问题是为什么我不能像往常一样设置名称属性值。

最佳答案

It returns Person. Why doesn't it return 'John' ?

因为 Object.create 行创建了一个以 Person 函数为原型(prototype)的对象,而 Person 函数对象有一个令人惊讶的定义name 属性,阻止您写入它。 (一旦了解这个定义就很有意义,但一开始会感到惊讶。)

当你做的时候你在创造什么

john = Object.create(Person);

...是一个使用 Person 函数作为其底层原型(prototype)的对象。这不会创建一个 Person instance(它将使用 Person.prototype 作为其原型(prototype)),它会创建一个实际使用该函数的对象对象 Person 本身作为原型(prototype)。

Person 函数有一个不可写的属性,叫做 name,它是函数的名字(这还没有在标准中,但它会在 ES6 中[目前它在 draft spec 的§9.2.11 中定义]并且 V8 已经这样做了)。因为该属性不可写john.name = 'John' 不执行任何操作。 (下面有更多关于不可写属性的信息。)

如果您的目标是使用 Person.prototype 作为对象的底层原型(prototype)来创建一个新对象,您可以:

john = new Person();

john = Object.create(Person.prototype);

因为 Person 接受一个参数,你可能会这样做

john = new Person('John');

...而不是之后分配给 name


关于不可写属性的更多信息:如果您还没有遇到过它们,它们在前一段时间被定义为第 5 版规范的一部分。这是一个例子:

var parent = {};
Object.defineProperty(parent, "foo", {
writable: false,
value: "original"
});

parent 对象有一个不可写的属性,foo:

console.log(parent.foo); // "original"
parent.foo = "bar";
console.log(parent.foo); // "original"

如果我们使用 parent 作为原型(prototype),我们仍然无法写入 foo,即使是在子对象上:

var child = Object.create(parent);
console.log(child.foo); // "original"
child.foo = "bar";
console.log(child.foo); // "original"

这就是您的代码中发生的事情。 parentPersonchildjohn

并且只是为了解决这个问题:如果我们想在此时为 child 创建一个可写属性,我们可以,但不是通过赋值,我们必须使用 defineProperty:

Object.defineProperty(child, "foo", {
writable: true,
value: child.foo // (just sets the initial value)
});
console.log(child.foo); // "original"
child.foo = "bar";
console.log(child.foo); // "bar"

现在 child 有它的 own 属性,叫做 foo,它隐藏(隐藏)了它原型(prototype)的 foo,并且是可写的。

关于javascript - Object.create 在 javascript : why does my code outputs Object instead of name string value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24840316/

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