javascript - 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 中是如何工作的......感谢您提供的任何帮助。
解决方案
使用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"
推荐阅读
- sql - 将 MS Access 数据库检索到 vb6 并使用 2 DTpicker 过滤数据以获得总和速率
- javascript - laravel5.8 上传头像前的图片预览
- python - WTForms:可选的验证器跳过,即使数据存在
- javascript - 通过 POST 从初始登录存储会话?
- git - git remove 在一个新分支中的提交,该分支是从 master 以外的分支意外创建的
- r - 在 mclapply : schedule cores 9 在用户代码中遇到错误,所有作业的值都会受到影响
- reactjs - React-select-checkboxes onClose 事件不起作用
- java - datastax cassandra java 驱动程序 PlainTextAuthProvider 示例
- ruby-on-rails - 无法自动加载常量 Chart,需要 chart.rb 来定义它
- java - 将eclipse与数据库连接