Javascript OOP帮助/建议/解释



嘿,我有个问题。我正在编写一个小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

定义对象时,在创建对象之前不能引用该对象。通过使用一个函数,您将延迟self.locationArray的查找,直到创建对象为止。

只有在执行语句之后,对象才会被分配给selfPageInfo。所以在陈述之后再做。

var self = PageInfo = {
    locationArray : window.location.pathname.toString().split("/"),
    printOutPath : function(){
        console.log(self.locationArray.length);
    },
    currentPage : function() { return self.locationArray[self.locationArray.length -2]; // works
    }
};
self.parentDirectory  =  self.locationArray[self.locationArray.length -3];

它将更新PageInfo

在函数内部使用this使其更具OO

var self = PageInfo = {
    locationArray : window.location.pathname.toString().split("/"),
    printOutPath : function(){
        console.log(this.locationArray.length);
    },
    currentPage : function() { return this.locationArray[this.locationArray.length -2]; // works
    }
};
self.parentDirectory  =  self.locationArray[self.locationArray.length -3];       

您还可以创建一个函数来设置parentDirectory

var self = PageInfo = {
    locationArray : window.location.pathname.toString().split("/"),
    printOutPath : function(){
        console.log(this.locationArray.length);
    },
    parentDirectory:"",
    setParentDirectory: function() {
         this.parentDirectory  =  this.locationArray[this.locationArray.length -3];  
    },
    currentPage : function() { return this.locationArray[this.locationArray.length -2]; }
};
self.setParentDirectory();

最新更新