嘿,我有一个问题。我正在编写一个小的 Js 对象,使我更容易管理我所在的页面,以便我能够在每页加载正确的脚本/样式。我遇到了一种我不明白的情况。我有一个属性 currentPage
显然足以设置为当前页面但是如果我只是直接从我之前定义的另一个属性设置它,它会返回一个引用错误,但是如果我把它放到一个函数中返回相同的东西,它有效。我不确定为什么会这样。谁可以给我解释一下这个?我不是核心 JS 开发人员,我只是边走边想,所以这是 JS 特有的东西吗?这是我的意思的代码示例:
var self = PageInfo = {
locationArray : window.location.pathname.toString().split("/"),
printOutPath : function(){
console.log(self.locationArray.length);
},
//ref. error to locationArray
parentDirectory : self.locationArray[self.locationArray.length -3],
currentPage : function() {
return self.locationArray[self.locationArray.length -2]; // works
}
};
最佳答案
当您使用 JavaScript 对象字面量语法(使用花括号 {}
创建对象)时,每个属性的值都是在创建对象时计算的表达式。它们无法引用同一对象的属性,因为该对象尚不存在。
请注意,在对象的方法中,您可以使用 this
而不是创建 self
变量。只要您使用像这样的点语法调用方法:
PageInfo.currentPage()
...在 this
方法中将自动引用该对象,因此您可以这样做:
var PageInfo = {
locationArray : window.location.pathname.toString().split("/"),
printOutPath : function(){
console.log(this.locationArray.length);
},
currentPage : function() { return this.locationArray[this.locationArray.length -2];}
};
alert( PageInfo.currentPage() );
进一步阅读:https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects
关于Javascript OOP 帮助/建议/解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9591716/