2011-02-12 25 views
1

考慮下面的代碼:Javascript:是否有關鍵字用於引用對象中的當前節點?

function Animal(){ 
    this.type = "dog"; 
    this.color = { 
       stomach: "white", 
       paws: "brown", 
       face: function(){ 
        if(this.color.stomach === "white"){ 
         return "red"; 
        }else{ 
         return "blue"; 
        } 
       } 
} 

這奇怪的彩色狗有臉的顏色取決於他的胃的顏色。我想知道是否有更簡單的語法寫法來編寫「this.color.stomach」部分。即,「這個」是指主要的動物對象。是否有一個類似的關鍵字引用了該關鍵字被調用的父對象?例如,由於我已經在Animal.color中,而不必重複該部分以獲取它的胃色(Animal.color.stomach),是否有一種方法可以直接引用顏色屬性,所以它會是像「parent.stomach」,其中「parent」是指它被調用的任何屬性 - 在這種情況下,Animal.color?

回答

2

你試過運行你的代碼嗎?因爲this實際上確實參考color而不是Animal對象。

這是如何工作的:this是指任何對象的函數被要求,一般情況下,你的face功能將被稱爲someAnimal.color.face() - 在這種情況下,this已經指color對象,所以this.color將是一個錯誤,而this.stomach實際上會工作。

+0

大鼠。我即將說出同樣的話。 – ClosureCowboy 2011-02-12 20:53:31

1
function Color(data) { 
    this.stomach = data.stomach; 
    this.face = data.face; 
} 

function Animal() { 
    var self = this; // self now refers to the animal 
    this.type = "Dog"; 
    this.color = new Color({ 
     face: function() { 
      // in the "face" function, "this" refers to the color 
      if (this.stomach === "white") { // color's stomach 
       return "red"; 
      } else if (self.type === "Dog") { // animal's type 
       return "Blue"; 
      } 
     } 
    }); 
} 
相關問題