我有:
// 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__ );
结果:
为什么?我做错了什么?
最佳答案
对于对象来说,没有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/