[英]Call an object function from within a callback function in Javascript
I have the following Javascript object: 我有以下Javascript对象:
var obj = (function (){
return{
functionOne: function(){}
functionTwo: function(){
$("#div").rotate(){
callback: function(){
functionOne(); // this doesn't work
}
});
}
}
}
When I am calling functionOne within a callback function from within functionTwo, functionOne is undefined. 当我从functionTwo内部的回调函数中调用functionOne时,functionOne未定义。 How can I call functionOne from withint the callback function of the rotate function (belongs to a plugin I use)? 如何从rotate函数的回调函数(属于我使用的插件)内部调用functionOne?
You could try setting the object you're returning to a variable first, and then referencing that: 您可以尝试先设置要返回变量的对象,然后再引用该对象:
var obj = (function(){
var o = {
functionOne: function(){
console.log('functionOne');
},
functionTwo: function(){
$("#div").rotate({
callback: function(){
o.functionOne();
}
});
}
};
return o;
})();
obj.functionTwo(); // logs "functionOne"
You could also use something like: 您还可以使用类似:
var o;
return o = {
...
};
Both ways do the same thing; 两种方式都做同一件事。 which one you want to use is a matter of personal preference and how readable you think they are. 您要使用哪一个取决于个人喜好以及您认为它们的可读性。
Inside functionTwo
, this refers to the object. 在functionTwo
内部,这是指对象。 So if you save a reference, you can call the function like so: 因此,如果您保存引用,则可以像下面这样调用该函数:
var obj = (function (){
return{
functionOne: function(){},
functionTwo: function(){
var o = this;
$("#div").rotate({
callback: function(){
o.functionOne(); // this does work
}
})
}
}
}());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.