我确信之前已经有人问过这些问题,但我真的找不到那个线程。
我写了类似下面的东西,但我不知道这种结构在javascript中的名称,让我们假设它的名称类似于(JSON结构中的Javascript)。
我需要知道这种结构的很多东西, 1) 它的实际名称是什么(如果有)? 2)如何在这个结构中获取parent.parent级别的变量,就像在SentenceBuilder.Section.get函数中一样,我需要获取SentenceBuilder.get函数,我已经尝试过this.this.get但它不起作用。 3)在此结构中声明只能在其函数内使用的私有(private)变量的最佳方法是什么。我试过_sentenceBuilder: new Object(),可以吗?
提前非常感谢...
var SentenceBuilder = {
_sentenceBuilder: new Object(),
_section: new Object(),
_group: new Object(),
_question: new Object(),
get: function () {
return this._sentenceBuilder; //for speeding up; --wasim
//return store.fetchSession("SENTENCE_BUILDER_" + VisitID);
},
set: function () {
store.saveSession("SENTENCE_BUILDER_" + VisitID, data);
this._sentenceBuilder = $(data);
},
Section: {
get: function () {
this.this._section = this.this.get().find("SECTION[SECTION_SEQ_NUM='" + sectionID + "']");
return this.this._section;
},
set: function () { },
},
Group: {
get: function () {
this.this._group = this.this.Section.get().find("GROUP[QUESTION_GROUP_ID='" + groupID + "']");
if (this.this._group.length == 0) {
this.this._question = this.this.Section.get().find("QUESTION[QUESTION_ID='" + questionID + "']");
this.this._group = this.this._question.parent();
}
return this.this._group;
},
set: function () { }
},
Question: {
get: function () {
this.this._question = this.this._group.find("QUESTION[QUESTION_ID='" + qId + "']");
return this._question;
},
set: function () { }
}
};
最佳答案
我不知道您是否在询问模块模式,但模块模式如下所示:
//Single Global Variable "Module"
var Module = ( function ( ) {
var privateVariable = "some value",
privateMethod = function ( ) {
//do something.
};
//returning one anonymous object literal that would expose privileged methods.
return {
//the method inside the return object are
//called as privileged method because it has access
//to the private methods and variables of the module.
privilegedMethod : function ( ) {
//this method can access its private variable and method
//by using the principle of closure.
alert(privateVariable); //accessing private variable.
privateMethod( ); //calling private method
}
};
})( );
这里的模块是向文档公开的单个全局变量。我们声明、调用一个匿名方法并将其分配给 Module 变量。
现在我们可以通过编写Module.privilegedMethod();
来调用privilegedMethod,模块内部的特权方法可以访问其私有(private)变量和私有(private)方法。因为,它们属于静态范围。如果我们有任何不想公开的数据或方法,我们可以将它们放在私有(private)方法中。
有关完整详细信息,请阅读 http://www.codeproject.com/Articles/247241/Javascript-Module-Pattern
关于javascript - JSON 类似 Javascript 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21455971/