javascript对象文字-嵌套函数和"this"关键词 [英] javascript object literal - nested functions and the "this" keyword
本文介绍了javascript对象文字-嵌套函数和"this"关键词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的示例中,当调用functionA()
时,this
关键字引用了包含的对象,因此我可以访问其属性(例如theValue
)
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
)
我的问题:我如何从嵌套 functionB()
内引用myObj
的属性?
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();
提前谢谢.
推荐答案
立即援救!
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 !!
您可以进一步分解它:
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;
}());
如果您熟悉OOP,则可以使用它来创建私有变量.
If you're familiar with OOP, you can use this to make private variables.
这篇关于javascript对象文字-嵌套函数和"this"关键词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文