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

Rob*_*cha 1 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__ );
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

为什么?我究竟做错了什么?

dfs*_*fsq 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
Run Code Online (Sandbox Code Playgroud)