来自两个地方的JavaScript命名空间和调用函数

时间:2018-06-07 15:58:10

标签: javascript

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

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

我想弄清楚的是,从init:代码块,我可以调用click事件中的代码('hello')吗?

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

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

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

我必须将事件参数从点击传递给你好。

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

2 个答案:

答案 0 :(得分:0)

使用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"

答案 1 :(得分:0)

您可以使用Javascript的强大功能之一 - Closures 。请参阅此MDN Documentation中的“闭包”主题。



var namespace = (function(){

    function hello(){
        alert("hello");
    }
    
    return {
      init: function (config) {
          console.log("called init");
          hello();
          console.log("called hello from init")
      },
      events: function () {
          $('#but').on('click', function (event) {
              hello();
              console.log("called hello from events")
          });
       }
    }
})();

namespace.init();
namespace.events();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="but">Click</button>
&#13;
&#13;
&#13;