Javascript function empty? What does it mean?

So, the short version, I do not understand, is a line of code:

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

In the long version, consider the following functions:

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);
                }
            })();
        };

This code is from Raphael's playground, which means that it implements the raphael library. Thus, the only line of code at the top that I do not understand (it is inside the try / catch expression), suppose to copy the code that the user enters, which is stored inside the cd.value into the function. But how is this possible?

You can visit the page here: http://raphaeljs.com/playground.html

+5
source share
5 answers

, 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

+4

Function

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

, . , .

Function

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

, cd.value() javascript, . ...

, cd.value.

+2

... :

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

: http://www.permadi.com/tutorial/jsFunc/index.html

+1

Function .

, , :

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

call paper .

+1

Function , . code, value - Javascript. , HTML- - :

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

  alert(a+b);
</textarea>

Now your sample code, if executed against this element code, will create the following function:

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

  alert(a+b);
}

You can take a look at the Mozilla Development Center for a feature to get a more complete explanation of how the object works Function.

+1
source

All Articles