【问题标题】:JavaScript create and assign a prototype object to another objectJavaScript 创建原型对象并将其分配给另一个对象
【发布时间】:2015-09-22 07:52:59
【问题描述】:

我有:

// 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 属性仅适用于函数对象。否则它只是另一个属性。

标签: javascript inheritance prototype prototypal-inheritance


【解决方案1】:

没有像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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多