我有下面這段代碼:獲取訪問範圍內的對象
<!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 。
那麼我需要做什麼來輸出例如約翰到控制檯?
感謝,
'return location;'?該函數運行後 - 「位置」對象不再可用(因爲沒有對它的活動引用) – zerkms
^that!當這個函數調用時,函數內部的'this'就是窗口,這就是'window'返回的原因。 – adeneo