2015-04-06 129 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