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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With