Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
70
rated 0 times [  72] [ 2]  / answers: 1 / hits: 22496  / 15 Years ago, thu, february 18, 2010, 12:00:00

i'm quite a newbie in javascript, and i'm spending some time trying to create namespaced objects in js.



Now, that's what i'm trying to do:



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();


I tried to include the nested class inside the first one, but it's not working also if i try:



this.nested = function() {

var mainObject = this;

return {
publicNestedMethod = function() {
mainObject.privateMethod();
}
}
}();


Someone can help me please? i'm gonna loose my mind on this.



Phaedra.


More From » class

 Answers
16

Closures are a lexical feature, not a semantic one. If the object is outside the lexical scope of another, it can no longer be nested and access the former's local variables. In the code of your nested function/class, there's no such thing as this.privateMethod, because privateMethod is never made to be a property of MainObject. It's simply a local variable inside a function.



There's no such things as private properties, private methods or private members in JavaScript. Hell, there's no such thing as a class. Some people like to emulate private members using local variables as above, but doing so results in cases like this, where the discrepancy between the two concepts comes and bites one in the behind.



To conclude, it is a bad idea to write Java code, with all its OO techniques in JS, just as it is a bad idea to write C code, with all its pointers and unbounded buffers, in C#. Sure, in both cases you can do it, but you would be failing to appreciate and exploit the language's features this way.



And now that I'm done with the rant, you can do something like this to get namespaced functions:



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();​

[#97543] Sunday, February 14, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shylaelisan

Total Points: 37
Total Questions: 94
Total Answers: 110

Location: Angola
Member since Tue, May 5, 2020
4 Years ago
;