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

JavaScript create and assign a prototype object to another object

我有:

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