0

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

below is a example API

jQuery.Test1 = (function(){

    _testFunction= function() {
        ...// do differently
    }


    return {
        // public
        callTest: function(){
            _testFunction()
        }
    }
}(jQuery))
user1595858
  • 3,218
  • 12
  • 51
  • 96
  • Oops, now that I spot your actual issue (haven't read the question properly) I'll have to mark it as a duplicate of [Difference between using var and not using var in JavaScript](http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript) :-) – Bergi Jul 01 '13 at 02:28

2 Answers2

5

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() of doOneThing. 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.

Community
  • 1
  • 1
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
3

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))
Dennis
  • 30,518
  • 9
  • 59
  • 75