我有一个 javascript 函数,它应该在点击时通过调用它之外的另一个函数来切换动画。
function MyFunction(id) {
var target = document.getElementById(id);
var on = true;
this.startMe = function() {
//animation code
on = true;
}
this.stopMe = function() {
//animation code
on = false;
}
this.toggleMe = function() {
if (on) this.stopMe();
else this.startMe();
}
target.addEventListener('click', function() {
this.toggleMe();
}, false);
}
问题出在 toggleMe 和 addEventListener 函数上。 “this”指的是函数本身,而不是包含它的函数,这是我需要它引用的。我该如何解决这个问题?
最佳答案
简单的解决方法是使用下面给出的闭包变量
function MyFunction(id) {
var self = this;
var target = document.getElementById(id);
var on = true;
this.startMe = function () {
//animation code
on = true;
}
this.stopMe = function () {
/animation code
on = false;
}
this.toggleMe = function() {
if (on) this.stopMe();
else this.startMe();
}
target.addEventListener('click', function() {
//this refers to the element here not the instance of MyFunction
//use a closure variable
self.toggleMe();
}, false);
}
另一种解决方案是使用 $.proxy() 将自定义执行上下文传递给回调- 你可以使用 Function.bind()也在 IE < 9 中但不支持
function MyFunction(id) {
var target = document.getElementById(id);
var on = true;
this.startMe = function () {
//animation code
on = true;
}
this.stopMe = function () {
//animation code
on = false;
}
this.toggleMe = function () {
if (on) this.stopMe();
else this.startMe();
}
//use Function.bind() to pass a custom execution context to
target.addEventListener('click', jQuery.proxy(function () {
// this refers to the element here not the instance of MyFunction
//use a closure variable
this.toggleMe();
}, this), false);
}
也可以使用 .click()/on('click')注册点击处理程序而不是 addEventListener
$(target).on('click', jQuery.proxy(function () {
// this refers to the element here not the instance of MyFunction
//use a closure variable
this.toggleMe();
}, this), false);
关于javascript - 如何在另一个 Javascript 函数之外调用一个 Javascript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21336551/