Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript object literal - nested functions and the "this" keyword

In the example below, when functionA() is invoked, the this keyword refers to the containing object, so I can access its properties (e.g. theValue)

My question: How do I refer to properties of myObj from within the nested functionB()?

var myObj = {
    theValue: "The rain in Spain", 
    functionA: function() {
        alert(this.theValue);
    },
    moreFunctions: {
        functionB: function() {
            alert(????.theValue);
        }
    }
}

myObj.functionA(); 
myObj.moreFunctions.functionB();  

Thanks in advance.

like image 392
Bumpy Avatar asked Jun 13 '13 23:06

Bumpy


1 Answers

Immediate invocation to the rescue!

var myObj = (function () {
    var that = {
        theValue: "The rain in Spain", 
        functionA: function() {
            alert(this.theValue); // or that.theValue, both work here
        },
        moreFunctions: {
            functionB: function() {
                alert(that.theValue);
            }
        }
    };
    return that;
}()); // <-- immediate invocation !!

You can decompose it even further:

var myObj = (function () {
    function functionA() {
        alert(that.theValue);
    }
    function functionB() {
        alert(that.theValue);
    }
    var that = {
        theValue: "The rain in Spain", 
        functionA: functionA,
        moreFunctions: {
            functionB: functionB
        }
    }
    return that;
}());

If you're familiar with OOP, you can use this to make private variables.

like image 196
Halcyon Avatar answered Nov 06 '22 21:11

Halcyon