开发者

What does this Javascript do? `new Function("_", "at" , "with(_) {return (" + text + ");}" )`

开发者 https://www.devze.com 2023-02-23 01:09 出处:网络
What is this line doing: var tfun = new Function(\"_\", \"at\" , \"with(_) {return (\" + text + \");}\" );

What is this line doing:

  var tfun = new Function("_", "at" , "with(_) {return (" + text + ");}" );

What is the _, at, and with(_)?

I've read this: http://www.permadi.com/tutorial/jsFunc/index.html

I understand that it's creating a new function object, but am still quite puz开发者_开发问答zled at what his is supposed to do.

Forgot to put the source: http://kite.googlecode.com/svn/trunk/kite.js

http://www.terrainformatica.com/2011/03/the-kite-template-engine-for-javascript/


Here a function is being created that will return the value of the key stored in the variable text on the object passed in to tfun().

When a new Function is created in this manner, the first arguments refer to the parameters of the function and the last argument is the function itself. So here we have two parameters named _ and at and then the function body.

with() is a statement saying to conduct the following lines of code within the context of the object specified. So with(_) is saying to conduct the return statement pulling the key text stored in _.

Here's an example:

var text = "name";
var obj  = { "name" : "Bob" };

var tfun = new Function("_", "at" , "with(_) {return (" + text + ");}" );

tfun( obj ); // returns "Bob"

I'm not sure why the at parameter is there as it's not being used.


First comes the function arguments, then code code, so it's basically the same as:

var tfun = function(_, at) {
  with(_) { return (eval(text)); };
}

So, whatever is in the text variable will be evaluated and returned from the function.

Note: The use of the eval function should generally be avoided, and as creating code dynamically from a variable does the same thing, it should also generally be avoided. There are a few situations where eval is needed, but most of the time it's not, so you should instead try find out the proper way of doing what you are trying to do.

0

精彩评论

暂无评论...
验证码 换一张
取 消