Reputation: 3890
The function name is mixed even if I am using a namespace. In the below example when I call nwFunc.callMe()
or $.Test1.callTest()
it will execute _testFunction()
of doOneThing
. I am expected for $.Test1.callTest()
to call _testFunction()
in $.Test1
API instead of one in doOneThing
. What I need to do to correct it?
Example:
var doOneThing = function() {
_testFunction= function() {
...
}
return {
// public
callMe: function(){
_testFunction();
}
}
}
var nwFunc = doOneThing();
nwFunc.callMe();
$.Test1.callTest();
jQuery.Test1 = (function(){
_testFunction= function() {
...// do differently
}
return {
// public
callTest: function(){
_testFunction()
}
}
}(jQuery))
Upvotes: 0
Views: 84
Reputation: 664620
You're not in an object literal, you are in a function body.
_testFunction: function() { .... // do differently }
is not an object property, but an anonymous function expression preceded by a label and is immidiately forgotten as it is not assigned anywhere. Make it a simple function declaration instead:
function _testFunction() {
.... // do differently
}
And
return { // public callMe() { _testFunction(); } }
is just a syntax error, in here you need the object literal sytnax:
return {
// public
callTest: function() {
_testFunction()
}
};
or
return {
// public
callTest: _testFunction // exporting the function directly
};
When I call
nwFunc.callMe()
or$.Test1.callTest()
it will execute_testFunction()
ofdoOneThing
. What I need to do to correct it?
You have to use a var
declaration to put your _testFunction
variable in a local scope. Currently you're writing to the global scope, where only one _testFunction
exists (currently in doOneThing
you're overwriting the _testFunction
from jQuery.Test1
, and both callTest
functions will invoke the new one). A function declaration would've fixed this as well (using the local scope), it is similar to a var statement + function expression.
Upvotes: 5
Reputation: 32598
You are mixing up your syntax slightly. You are using object literal notation when you declare the function originally and using function declaration notation when actually creating the object, so you should switch the two:
jQuery.Test1 = (function(){
function _testFunction() {
.... // do differently
}
return {
// public
callTest: _testFunction
}
}(jQuery))
Upvotes: 3