I like to organize my javascript in namespace style like below. What I want to know : is there another (shorter?) way to call myFirstFunction() from mySecondFunction()? I tried this.myFirstFunction() and it’s not working so maybe there’s some kind of mysterious trick here that I don’t know.
var myNameSpace = {
myFirstFunction: function(){
alert("Hello World!");
},
mySecondFunction: function(){
myNameSpace.myFirstFunction();
}
}
Thanks for your help as usual, people of SO! 🙂
As written in your example code,
this.myFirstFunction()would work. Your code is likely simplified to illustrate your problem, so it would probably help to see the actual code to tell why it doesn’t work withthis.One possible reason that it fails would be if the code where you call
this.myFirstFunction()is inside a closure. If so,thiswould be a reference to the closing function, not your namespace and would therefore fail. See here for a contrived example based on your code to see what I mean. Again, having a look at the actual code would probably be helpful to diagnose what’s going on.