Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

You can simply use myObj:

alert(myObj.theValue);

Check demo http://jsbin.com/izugon/2/edit

A common practice is to define a "self" variable and use that rather than the this keyword. This helps when you wish to add scope or create a class.

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

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

Another possibility is to use the ECMA5 Function.prototype.bind method. To put it simply, you can bind a method's this keyword. Follow the link or use a search engine for more details. If you use this method, beware that it is not compatible with older browsers, but the provided link shows an alternate implementation you may use to implement the .bind method in older browsers.

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

myObj.functionA();
myObj.moreFunctions.functionB();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top