gpt4 book ai didi

JavaScript 创建原型(prototype)对象并将其分配给另一个对象

转载 作者:行者123 更新时间:2023-11-30 08:36:12 25 4
gpt4 key购买 nike

我有:

// prototype object
var x = {
name: "I am x"
};

// object that will get properties of prototype object
var y = {};

// assign the prototype of y from x
y.prototype = Object.create( x );

// check
console.log( y.__proto__ );

结果:

enter image description here

为什么?我做错了什么?

最佳答案

对于对象来说,没有prototype 这样的特殊属性,它的行为类似于函数。你想要的只是 Object.create( x );:

var x = {
name: "I am x"
};

// object that will get properties of prototype object
var y = Object.create( x );

// check
console.log( y.__proto__ );

// verify prototype is x
console.log( Object.getPrototypeOf(y) === x ); // true

关于JavaScript 创建原型(prototype)对象并将其分配给另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31224308/

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