Search code examples
javascriptbackbone.jsmocha.jsbackbone-views

Reading a variable value inside a named function in javascript


This may be very simple but i lost my way in finding the answer,

I have a named function inside a Backbone view. I'm trying to write unit test for this named function and i could see a variable is being declared in function scope. The state of this variable changes based on certain scenarios.

I have instantiated the view object inside my test suite and when i do a console.log(viewObject.namedFunction) i see the entire function being logged properly. Now how do i access the variable inside the namedFunction, i was expecting something like viewObject.namedFunction.variableName but it will not work and when i did that, it was not working as expected.

If the variable is tied to viewObject scope then it would have been easy to access it. But in this scenario it is not so can some one please help me in getting a hold on the variable inside named function in view object from test suite.


Solution

  • I think I understand your confusion, because when you define a variable using var in the window scope, it becomes a property on the window object... It would seem to follow that when you define a variable in a child scope, it should become a member of the local context, right? Nope. Globals are special ;-)

    In fact, if that were the case, there would be no privacy!

    If you want sign to be public, be explicit.

    obj = {
        namedFunction : function myself() {
            console.log(myself);
            myself.sign = 23;
        }
    };
    obj.namedFunction.sign;
    

    The only problem with this approach is that you can now assign a new value to sign from anywhere. The classic and preferred approach to this problem is to create a getter function for your private variable.

    var obj = {
        namedFunction : function myself() {
            var sign = 3;
            myself.getSign = function(){return sign;};
        }
    };
    obj.namedFunction.getSign();
    

    This isn't by any means the only approach, but I hope it was helpful.