我有很多非常相似的函数,它们做不同的事情,我正在尝试重构它。下面我创建了一个generic_command
:
function generic_command(name, run){
var start_position = $('textarea').prop('selectionStart'),
end_position = $('textarea').prop('selectionEnd'),
current_command = { command : name, last_start_position : start_position, last_end_position : end_position }
if(current_command == last_command){
original_content = $('textarea').val()
run // different code needs to be executed here!
last_command = current_command
}
}
实际上,函数中唯一发生变化的是在 run
处运行的代码。
我尝试这样调用它:
$('#remove_bold').bind('click', function(){
generic_command('remove_bold', remove_character(start_position), remove_character(end_position - 2 ))
});
但是,这不起作用,因为在监听器调用时,start_position
和 end
位置未定义。
我猜如果我像 eval(run)
那样评估 run
,它会起作用,但我不想使用 eval
> 因为这是不安全的。
我应该创建一个 generic_command 类并创建它的实例吗?我该怎么做呢?能给个例子吗?
最佳答案
你可以通过函数式思考来解决这个问题。您可以使用的方法是传入一个函数,该函数将所需的值作为参数,然后对它们执行您需要的任何操作。像这样:
// run should be a function that takes a command object as its parameter
function generic_command(name, run) {
var start_position = $('textarea').prop('selectionStart'),
end_position = $('textarea').prop('selectionEnd'),
current_command = {
command: name,
start_position: start_position,
end_position: end_position
};
if (current_command == last_command) {
original_content = $('textarea').val();
run(current_command);
last_command = current_command;
}
}
然后你可以像这样实现你的事件处理程序:
$('#remove_bold').bind('click', function(){
generic_command('remove_bold', function(command) {
remove_character(command.start_position);
remove_character(command.end_position - 2 );
});
});
顺便说一句,我认为您在这里仍然存在逻辑问题,因为在上面的函数中 current_command == last_command
将始终为 false
。
关于javascript - 创建通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23790650/