我有一个对象,它有点简化:
function obj(arg){
return{
fct1: function(){
$(".output").append("called fct1 with arg: "+arg+"<br>");
},
fct2: function(){
$(".output").append("called fct2, which has an other function, which calls fct1<br>");
fct2a();
function fct2a(){
$(".output").append("doing something else, then calling fct1<br>");
this.fct1(); //not within scope
}
}
}
}
var myobj = obj("asd");
myobj.fct2();
我想从fct2a调用fct1,怎么样? Fiddle
答案 0 :(得分:3)
为该var创建一个temp var和asign this
对象并从中调用。请找到以下代码
function obj(arg){
return{
var temp=this;
fct1: function(){
$(".output").append("called fct1 with arg: "+arg+"<br>");
},
fct2: function(){
$(".output").append("called fct2, which has an other function, which calls fct1<br>");
fct2a();
function fct2a(){
$(".output").append("doing something else, then calling fct1<br>");
temp.fct1();
}
}
}
}
var myobj = obj("asd");
myobj.fct2();
答案 1 :(得分:0)
您也可以单独声明fct1()
并在需要的地方调用它:
function obj(arg){
function innerFct1(arg) {
$(".output").append("called fct1 with arg: "+arg+"<br>");
}
return{
fct1: innerFct1,
fct2: function(){
$(".output").append("called fct2, which has an other function, which calls fct1<br>");
fct2a();
function fct2a(){
$(".output").append("doing something else, then calling fct1<br>");
innerFct1("arg2"); //not within scope
}
}
}
}
var myobj = obj("asd");
myobj.fct2();