JavaScript创建并将原型对象分配给另一个对象

时间:2015-07-04 19:15:06

标签: javascript inheritance prototype prototypal-inheritance

我有:

// 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

为什么呢?我做错了什么?

1 个答案:

答案 0 :(得分:5)

对于与函数类似的对象,没有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
相关问题