javascript - 如何在另一个 Javascript 函数之外调用一个 Javascript 函数?

标签 javascript jquery

我有一个 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/

相关文章:

c# - 小数点无法通过 JSON 回发正确传递到 C#

javascript - 如何使用 jQuery 正确选择下一个 div

javascript - 在控制台中使用 javascript 构建棋盘

javascript - 用于获取 ngTableParams 的通用排序功能不适用于非分组表

javascript - JQuery 会干扰 bokeh.js。为什么?

javascript - jQuery如何在每个分号后插入<br/>标签

javascript - 当 promise 被多次解决时会发生什么

javascript - 在 hapi.js 中设置标题

javascript - 如何检查水平 slider 是在开头还是结尾

javascript - 在编辑链接上首次加载页面时如何保留值