2015-04-06 101 views
1

我有下面這段代碼:獲取訪問範圍內的對象

<!DOCTYPE html> 
<html> 
<body> 

<script> 
function zz(){ 
var location = { 
    firstName: "John", 
    lastName : "Doe", 
    id  : 5566, 
    fullName : function() { 
     return this.firstName + " " + this.lastName; 
    } 
}; 
return this; 
} 

var abc= zz(); 
console.log(abc); //This works, but it is the the window objects location, I want the location I have defined 
console.log(some code here to print out John); 
console.log(some code here to print out Doe); 
</script> 
</body> 
</html> 

我選擇的位置作爲對象名稱來了解更多關於範圍衝突。

但現在我無法弄清楚如何到達我定義的變量。我知道我有一個對象命名位置包裝在一個函數zz

我知道對象的位置有一個firstName屬性約翰 我也知道對象的位置有一個方法fullName將返回到調用參考的John Doe 。

那麼我需要做什麼來輸出例如約翰到控制檯?

感謝,

+1

'return location;'?該函數運行後 - 「位置」對象不再可用(因爲沒有對它的活動引用) – zerkms

+0

^that!當這個函數調用時,函數內部的'this'就是窗口,這就是'window'返回的原因。 – adeneo

回答

0

如何:除了使用var,分配屬性this。而且由於它看起來像是在嘗試構建對象構造函數,請嘗試使用new關鍵字。

 function zz() { 
      this.location = { 
       firstName: "John", 
       lastName: "Doe", 
       id: 5566, 
       fullName: function() { 
        return this.firstName + " " + this.lastName; 
       } 
      }; 

      this.getFirstName = function() { 
       return this.location.firstName; 
      }; 

      this.getLastName = function() { 
       return this.location.lastName; 
      }; 

     } 

     var abc = new zz(); 
     console.log(abc); // zz { location={...}, getFirstName=function(), getLastName=function()} 
     console.log(abc.getFirstName(), abc.location.firstName); //John, John 
     console.log(abc.getLastName(), abc.location.lastName); //Doe, Doe 
     console.log(abc.location.fullName()); //John Doe 
+1

好的辣椒醬就是我想要的。顯然,我錯過了當時我不知道的new()。我很感謝你對此的回答和見解! – JimF

1

var s爲只有它們與關鍵字var限定的範圍內使用。我很確定你實際上想在你的location對象中想要this來引用你的location對象,而你可能需要zz中的更多方法。下面是如何實現:

function zzLoc(context){ 
    this.firstName = 'John'; 
    this.lastName = 'Doe'; 
    this.id = 5566; 
    this.fullName = function(){ 
    return this.firstName+' '+this.lastName; 
    } 
    this.parent = context; 
} 
function zz(){ 
    this.location = function(){ 
    return new zzLoc(this); 
    } 
    // more methods here 
} 
var wellNow = new zz, loc = wellNow.location(); 
console.log(loc.fullName()); 
+0

PHPGlue謝謝你的回答!我計劃研究你們和辣椒雀,以瞭解相似之處和不同之處。 – JimF