gpt4 book ai didi

javascript - 从字符串调用 javascript 函数

转载 作者:行者123 更新时间:2023-12-01 01:50:27 26 4
gpt4 key购买 nike

我的 javascript 模块中有以下代码,但这需要我使这些函数对外界可见。

var mymodule = function() {
var self = null,
init = function () {
self = this;
$('.actionButton').click(function () {
var worklistId = $(this).data('worklistid'),
action = $(this).data('action');
self[action] && self[action](worklistId); //watchout methods marked as not used are used by this invocation
})
},
send = function () {
// some logic
},
finish = function () {
// some logic
},
delete = function () {
// some logic
};

return {
init: init,
send: send,
finish: finish,
delete: delete
};
}();

mymodule.init();

所以我想在模块中返回的唯一内容是 init 函数。但是,当我这样做时,我无法调用这些函数,因为对象(自身)仅包含在外部可见的 init 函数。

return {
init: init
};

是否有任何解决方案可以像这样调用我的函数而不使它们对外界可见?请不要使用 if else 语句,因为我的工作流程比本示例中的 3 个操作更大。我想让我的模块尽可能封闭,因为这可以减少依赖性。

更新

这是一个更新的 jsfiddle,其中包含建议的解决方案之一,但这给了我另一个问题。 http://jsfiddle.net/marcofranssen/bU2Ke/

最佳答案

像这样的东西会起作用:

var mymodule = function() {
var self = this;
init = function () {

$('.actionButton').click(function () {
var worklistId = $(this).data('worklistid'), action = $(this).data('action');
self[action] && self[action](worklistId); //watchout methods marked as not used are used by this invocation
})
}
self.send = function () {
console.log('send');
}
self.finish = function () {
console.log('finish');
}
self.delete = function (item) {
console.log('delete');
};

return {
init: init,
};
}();

mymodule.init();​

这是 fiddle :

http://jsfiddle.net/yngvebn/SRqN3/

通过在 init 函数外部将 self 变量设置为 this,并附加 sendfinishdelete 函数到 self,您可以在 init 中使用 self[action] 语法 -功能

关于javascript - 从字符串调用 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12262428/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com