Pha*_*dra 12 javascript nested private class
我是javascript的新手,我花了一些时间尝试在js中创建命名空间对象.
现在,这就是我想要做的:
MainObject = function() {
var privateVariable = "i'm private";
var privateMethod = function() {
// doSomething
}
this.publicMethod = function() {
// doPublicSomething
}
}
MainObject.prototype.nested = function() {
this.publicNestedMethod = function() {
// that's not working at all
this.privateMethod(privateVariable);
}
}
MyObject = new MainObject();
MyObject.publicMethod();
MyObject.publicNestedMethod();
Run Code Online (Sandbox Code Playgroud)
我试图在第一个中包含嵌套类,但如果我尝试它也不起作用:
this.nested = function() {
var mainObject = this;
return {
publicNestedMethod = function() {
mainObject.privateMethod();
}
}
}();
Run Code Online (Sandbox Code Playgroud)
有人可以帮帮我吗?我会放松心情.
淮德拉.
Max*_*keh 14
闭包是一个词法特征,而不是语义特征.如果对象在另一个的词法范围之外,它就不能再"嵌套"并访问前者的局部变量.在嵌套函数/类的代码中,没有这样的东西this.privateMethod,因为privateMethod它永远不会成为属性MainObject.它只是函数内的局部变量.
JavaScript中没有"私有属性","私有方法"或"私有成员"之类的东西.天哪,没有"阶级"这样的东西.有些人喜欢使用如上所述的局部变量来模拟私有成员,但这样做会导致这样的情况,两个概念之间的差异就会出现并在后面咬一个.
总而言之,用JS中的所有OO技术编写Java代码是一个坏主意,就像用C#编写C代码及其所有指针和无界缓冲区一样.当然,在这两种情况下你都可以做到,但你不会以这种方式欣赏和利用语言的功能.
现在我已经完成了咆哮,你可以做这样的事情来获得"命名空间"功能:
MainObject = function() {
var privateVariable = "I'm private";
var privateMethod = function() {
alert('Private');
}
this.publicMethod = function() {
alert('Public');
}
this.nested = {
publicNestedMethod: function() {
privateMethod();
}
};
// or
this.nested = (function() {
var nestedPrivate = 5;
return {
publicNestedMethod: function() {
alert(nestedPrivate);
privateMethod();
}
};
})();
}
MyObject = new MainObject();
MyObject.publicMethod();
MyObject.nested.publicNestedMethod();?
Run Code Online (Sandbox Code Playgroud)
对"私人"方法使用下划线约定是保持组织有序的合理方法.
MainObject = function() {
this._privateVariable = "i'm private";
this._privateMethod = function() {
// doSomething
}
this.publicMethod = function() {
// doPublicSomething
}
}
Run Code Online (Sandbox Code Playgroud)