空的Javascript函数?这是什么意思?

Kho*_*hoi 5 javascript raphael

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

(new Function("paper", "window", "document", cd.value)).call(paper, paper);
Run Code Online (Sandbox Code Playgroud)

长版本,看看这些功能:

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);
                }
            })();
        };
Run Code Online (Sandbox Code Playgroud)

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

您可以访问以下页面:http://raphaeljs.com/playground.html

luc*_*eer 4

你明白是什么new Function()意思吗?它的相似之处eval()在于它需要一串 JavaScript 代码 - 它使用该字符串来定义一个函数。因此,您发布的行相当于执行以下操作:

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

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