簡體   English   中英

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM