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

标签 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

为什么?我做错了什么?

最佳答案

对于对象来说,没有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/

相关文章:

java - Java 中的构造函数保证了哪些属性?

c++ - 将基类指针转换为未知的派生类指针

inheritance - Lua元表__index定位的区别

javascript - 为什么对象原型(prototype)显示为 html 属性?

node.js - 为什么会忘记对象的原型(prototype)?

javascript - Chrome 扩展程序 "Receiving end does not exist."错误

javascript - Angular cli 项目 - 更改路线时脚本未正确加载

javascript - 砌体和谷歌地图的图像重叠不占用分割宽度

javascript - Stripes:无法添加到通过 javascript 动态创建的表格中

javascript - 在不覆盖当前函数体的情况下扩展 javascript 函数