簡體   English   中英

JavaScript構造函數和原型問題

[英]Javascript constructor and prototype issue

我有以下代碼,我感到困惑,為什么當我定義屬性“ name”的原型時,它顯示為“ 40”而不是“ fred”? javascript內部發生了什么? 這似乎是一個簡單的問題,但我對此感到困惑。 謝謝!

function Product(id){
    this.id = id
    this.name = id + 20
}

Product.prototype.name = 'fred';
var p = new Product(20);
console.log(p.name);

因為您做了this.name = id + 20

p.name將首先在實例中找到name屬性,如果找不到,請嘗試在原型中查找。

function Product(id){
    this.id = id
}

Product.prototype.name = 'fred';
var p = new Product(20);
console.log(p.name); // then it will be fred

暫無
暫無

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

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