我的代码如下:
<!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输出到控制台?
谢谢,
答案 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