今天在CSDN 上遇到这么一个问题:
var obj = {
instance:"demo",
str:{
text:function()
{
//问这里如何访问 instance
}
},
fortest:function(){
alert(this.instance);
}
}
通过分析,这是一个 obj 对象,其中包含另一个对象 str,str 包含函数 text,由于 str 并不知道它会被谁包含,所以它也就不知道 obj 中的任何内容(除了它自己),也就无法访问 instance 了,但我们可以这样做:
var obj = {
instance:"demo",
str:{
text:function()
{
alert(obj.instance);
}
},
fortest:function(){
alert(this.instance);
}
}
obj.str.text();
这样就解决了访问 instance 的问题,但这种局限性比较小,如果把 str 对象放在其它地方,obj 对象就失效了,改为:
var obj = {
instance:"demo",
str:{
text:function(myobj)
{
alert(myobj.instance);
}
},
fortest:function(){
alert(this.instance);
}
}
obj.str.text(obj);
text 函数使用哪个对象的 instance,由参数 myobj 说了算,注意最后面一句,把 obj 作为参数传进去了的。
相关阅读