我有下面这段代码:获取访问范围内的对象
<!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