簡體   English   中英

原型如何通過“ this”訪問構造函數的成員?

[英]How does prototype get access to constructor function's members through “this”?

考慮以下代碼:

  function Plant () {
        this.country = "Mexico";
        this.color= "yellow";
    }

    Plant.prototype.showDetails = function() {
        console.log("I am from " + this.country + " and my color is " + this.color); 
    }  

    var banana = new Plant();
    banana.showDetails(); //this outputs "I am from Mexico and my color is Yellow".

現在我的問題是,即使showDetails不在功能的外部,它如何訪問Plant功能的國家和顏色屬性? (Javascript具有按函數的作用域,詞法作用域)。

我進行了一些自省,發現當調用banana.showDetails時,“ this”是指Plant對象而不是香蕉對象。 為什么會這樣呢? 在JS中,“ this”是指調用函數的對象,在這種情況下為香蕉對象。

countrycolor不是Plant功能的屬性; 它們是調用Plant時與this對象綁定的任何對象的屬性。

new Plant()創建一個新的對象,然后調用Plantthis綁定到新的對象。

(從某種意義上講,每個JavaScript函數都有兩個參數thisarguments ,這是由每個函數調用設置的(免責聲明:不適用於“胖箭頭”樣式的函數)。)

以下代碼在道德上與您的代碼等效,只是不使用構造函數/方法:

function Plant(x) {
    x.country = "Mexico";
    x.color = "yellow";
    return x;
}

function showDetails(x) {
    console.log("I am from " + x.country + " and my color is " + x.color); 
}  

var banana = Plant({});
showDetails(banana);

您將香蕉對象創建為新的Plant對象,因為您沒有定義它自己的屬性,因此使用Plant中定義的屬性。 如果您在香蕉上定義屬性,如下所示: banana.country = "Serbia"; banana.color = "red"; banana.country = "Serbia"; banana.color = "red"; 那么您將從香蕉屬性中獲得價值。 因此,基本上,這是指香蕉,但是香蕉使用從Plant繼承的屬性。

暫無
暫無

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

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