Is there a way for an inn开发者_JS百科er object (t1) to access its container object.
var t = {
fnc1: function(){
alert("fnc1");
},
t1: {
fnc2: function(){
alert("fnc2");
},
fnc3: function(){
this.fnc1();
}
}
};
t.t1.fnc3();
when executing the following code i get an error 'this.fnc1 is not a function' since the this is referring to the t1 object and not the t object.
Is there any way to access the fnc1?
Sure, as long as you don't overwrite the variable:
t.fnc1()
If you want to call fnc1()
as a method of t.t1
, use call()
or apply()
.
Trying to use Javascript as a pure OO language, drives often to many frustrations.
You could try to use instead the Javascript specific features, mainly functions and closures.
I took you example and made a variant of it:
var t = function(){
var str = "fnc",
fnc1 = function(){
alert( str + "1");
};
return {
fnc1:fnc1,
t1:{
fnc2:function(){
alert( str + "2");
},
fnc3:fnc1
}
};
};
t().t1.fnc3();
精彩评论