5

所以简短的版本,我不明白的是这行代码:

(new Function("paper", "window", "document", cd.value)).call(paper, paper);

长版,看看这些功能:

window.onload = function () {
            var paper = Raphael("canvas", 640, 480);
            var btn = document.getElementById("run");
            var cd = document.getElementById("code");

            (btn.onclick = function () {
                paper.clear();
                paper.rect(0, 0, 640, 480, 10).attr({fill: "#fff", stroke: "none"});
                try {
                    (new Function("paper", "window", "document", cd.value)).call(paper, paper);
                } catch (e) {
                    alert(e.message || e);
                }
            })();
        };

这段代码来自 Raphael playground,这意味着它实现了 raphael 库。因此,我不理解顶部的单行代码(它在 try/catch 表达式中),假设将用户输入的存储在 cd.value 中的代码复制到函数中。但这怎么可能?

您可以在此处访问该页面:http ://raphaeljs.com/playground.html

4

5 回答 5

4

你明白什么new Function()吗?它类似于eval()它需要一个 javascript 代码字符串 - 它使用该字符串来定义一个函数。所以你发布的那行相当于做:

(function(paper,window,document){
  /* the code in the cd.value string goes here */
}).call(paper,paper);

更多信息:https ://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Function

于 2010-07-18T03:06:28.597 回答
2

函数类构造函数

functionName = new Function("function code should be written here");

此构造将代码评估为字符串,并且比分配匿名函数要慢得多。它只应在实际需要的地方使用。

带参数的 Function 类构造函数

functionName = new Function("varName","varName2","etc.","function code");

它看起来像cd.value()提供了一个带有 javascript 代码的字符串,它将被解析和编译。以后叫它...

您应该检查代码的cd.value外观。

于 2010-07-18T03:04:26.557 回答
1

它基本上是创建一个具有动态主体的新函数对象......我能解释它的最好方法是这样的:

function (paper, window, document) where {} = cd.value;

这是阅读更多信息的资源:http ://www.permadi.com/tutorial/jsFunc/index.html

于 2010-07-18T03:05:36.733 回答
1

Function函数创建一个新的函数实例,最后一个参数作为函数的代码。

所以它基本上与以下内容相同:

eval("function(paper,window,document){"+cd.value+"}").call(paper, paper);

call方法只需使用paper数组中的项目调用函数作为参数。

于 2010-07-18T03:11:47.383 回答
1

参数Function是函数的命名参数,然后是函数体。在这种情况下,您有一个 id 为的元素,该元素codevalue属性是一些 Javascript 代码。假设您在文档中的某处有此 HTML:

<textarea id="code">
  var a = "foo";
  var b = "bar";

  alert(a+b);
</textarea>

现在,如果针对此code元素运行您的代码示例,将创建以下函数:

function(paper, window, document) {
  var a = "foo";
  var b = "bar";

  alert(a+b);
}

您可以查看Mozilla 开发中心关于 Function 的文档,以更全面地了解该Function对象的工作原理。

于 2010-07-18T03:14:14.640 回答