Bum*_*mpy 11 javascript object this literals
在下面的示例中,functionA()调用when时,this关键字引用包含对象,因此我可以访问其属性(例如theValue)
我的问题:如何myObj在嵌套中 引用from的属性functionB()?
var myObj = {
theValue: "The rain in Spain",
functionA: function() {
alert(this.theValue);
},
moreFunctions: {
functionB: function() {
alert(????.theValue);
}
}
}
myObj.functionA();
myObj.moreFunctions.functionB();
Run Code Online (Sandbox Code Playgroud)
提前致谢.
立即援引救援!
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 !!
Run Code Online (Sandbox Code Playgroud)
您可以进一步分解它:
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;
}());
Run Code Online (Sandbox Code Playgroud)
如果您熟悉OOP,则可以使用它来创建私有变量.
您可以简单地使用myObj:
alert(myObj.theValue);
Run Code Online (Sandbox Code Playgroud)
查看演示http://jsbin.com/izugon/2/edit