首页 > 解决方案 > JavaScript 命名空间和来自两个地方的调用函数

问题描述

我已经选择了一些 JavaScript 来处理如下(非常简化!)

var namespace = {
    init: function (config) {
        // do stuff, all ok so far
    },
    events: function () {
        $('#id').on('click', '.class', function (event) {
                alert('hello')
}
}};

我想弄清楚的是如何从 init: 代码块中调用执行警报('hello')的 click 事件中的代码?

我意识到将 alert('hello') 移动到函数中会有所帮助(因此我可以从 init 调用该函数并单击),但是我将如何在此命名空间中定义该函数并从两个地方调用它?

我的目标是,猜测解决方案是这样的:

var namespace = {
    init: function (config) {
        // do stuff
        hello
    },
    hello: function() {
        alert('hello');
    },
    events: function () {
        $('#id').on('click', '.class', function (event) {
            hello
    }
};

我必须将事件参数从 click 传递到 hello。

我仍在试图弄清楚命名空间在 js 中是如何工作的......感谢您提供的任何帮助。

标签: javascript

解决方案


使用this关键字。

var namespace = {
    init: function (config) {
        // do stuff
        this.hello();
    },
    hello: function() {
        alert('hello');
    },
    events: function () {

        $('#id').on('click', '.class', function (event) {
            this.hello();
        }.bind(this));
    }
};

如何使用它的示例:

namespace.init();
namespace.events(); // then do a click on the html where you have the class "class"

推荐阅读