在Javascript中将字符串转换为函数

Convert String to Function in Javascript

本文关键字:转换 函数 字符串 Javascript      更新时间:2023-09-26

我在从字符串创建新函数时遇到了一个小问题。示例:我有一个div和一些按钮。其中一个按钮只是让我的div动画化,其他什么都没有。但另一个按钮使div动画化,动画完成后,调用一个新函数。

我必须将新的、后续的函数作为一个变量来处理,因为在div动画化之后,我必须调用很多函数。

下面是我举的一个例子:http://jsfiddle.net/AmVSq/3/.我希望你能理解我的问题。

我在JavaScript中找到了new Function();,但它让我产生了疑问,JS控制台也没有记录任何内容。

有人能告诉我我做错了什么吗?非常感谢。。

在JavaScript中,函数是"第一类"对象。这意味着您可以将它们分配给变量,并将它们作为参数传递给其他函数。

当您可以传递函数名称本身时,不需要从字符串创建函数,如下所示:

<div><a href="javascript:void(0)" onclick="close_div( alert_me );">Close Div then do something</a></div>

和脚本:

function close_div( next_function ) {
    $('#wrap').animate({ 'height': '-=100px' }, 300, function() {
        if ( next_function ) {
            // do the following function
            next_function();
        }
    });
}

--jsFiddle演示---

事实上,出于您的目的,您可以简单地将next_function直接传递给animate函数,如下所示:

function close_div( next_function ) {
    $('#wrap').animate({ 'height': '-=100px' }, 300, next_function);
}

没有必要检查next_function是否为undefined,因为.animate会为您执行此操作。

您做错的是使用new Function。正确的方法是只传递函数,这些函数和JavaScript中的其他对象一样:

http://jsfiddle.net/minitech/AmVSq/6/

<div><a href="javascript:void(0)" onclick="close_div();">Close Div</a></div>
<div><a href="javascript:void(0)" onclick="close_div(alert_me);">Close Div then do something</a></div>
<div><a href="javascript:void(0)" onclick="close_div(confirm_me);">Close Div then do another thing</a></div>
<div id="wrap"></div>​
function close_div( next_function ) {
    $('#wrap').animate({ 'height': '-=100px' }, 300, function() {
        if(next_function) {
            next_function();
        }
    });
}
function alert_me() {
    alert( 'The animation is complete' );
}
function confirm_me() {
    confirm('Are you sure?');
}

或者,更简洁地说,$('#wrap').animate({height: '-100px'}, 300, next_function);

chrome控制台正确显示结果:

> f = new Function("alert('hello');");
function anonymous() {
  alert('hello');
}
> f(); //executes it.

但是,使用字符串来创建函数,或者将字符串传递给函数来执行它,实际上是一种糟糕的做法。

function test(callback) {
    callback();
}
test(function() { alert("hello"); });

您不需要将函数制作成字符串,您可以将函数作为参数传递给Javascript中的其他函数。

例如:

function get_message1() {
    return "hello world";
}
function get_message2() {
    return "yay for first-class functions";
}
function print_message(message_func) {
    console.log(message_func())
}
print_message(get_message1);
print_message(get_message2);