获取对范围对象的访问权限

时间:2015-04-06 22:35:34

标签: javascript scope

我的代码如下:

<!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>

我选择location作为对象名称,以了解有关范围碰撞的更多信息。

但现在我无法弄清楚如何获得我定义的变量。我知道我有一个名为location的对象包含在函数zz

我知道对象位置具有John的firstName属性 我知道对象位置还有一个方法fullName,它将John Doe返回给调用引用。

那么我需要做什么才能将John输出到控制台?

谢谢,

2 个答案:

答案 0 :(得分:1)

var仅在使用关键字var定义的范围内可用。我确定您确实希望this对象中的location引用您的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());

答案 1 :(得分: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