我在JavaScript中注意到,如果你定义一个函数,比如myfunction()然后调用myfunction.toString(),你会得到该函数的源文本.这有什么有趣/现实世界的用途吗?
Guf*_*ffa 14
好吧,你可以用它来轻松重新定义一个函数:
function x() { alert('asdf'); }
eval(x.toString().replace('asdf','hello'));
x();
Run Code Online (Sandbox Code Playgroud)
这将提醒字符串"hello"而不是字符串"asdf".
这可能很有用.另一方面,由于难以维护代码,自修改代码通常不受欢迎......
jsd*_*sdw 10
这是一个老问题,但这是我的2美分.
使用node.js,这对于在服务器端创建函数非常有用,然后将这些函数嵌入到页面中并发送到客户端.
例如,dot.js模板引擎首先将模板编译为函数,然后可以执行该函数以生成HTML代码.
例如:
var compiled = dot.compile("<h1>{{=it.header}}</h1>");
var html_output = compiled({header: "hello world"});
Run Code Online (Sandbox Code Playgroud)
因此,如果我们想在客户端中使用模板而不需要每个客户端首先编译它们,我们可以为它们提供一个包含评估结果的页面:
"var compiled = " + dot.compile("<h1>{{=it.header}}</h1>").toString();
Run Code Online (Sandbox Code Playgroud)
然后,它将提供一个"编译"功能客户端,用于编译数据,例如从ajax请求发送到HTML客户端的数据.
我用它来自动生成函数的命名参数版本.例如,如果您有一个功能
function f(a, b, c) {
return a * b + c;
}
Run Code Online (Sandbox Code Playgroud)
你可以从中提取参数名称f.toString()并使用它来生成一个你可以这样调用的函数:
namedParametersF({ a: 2, b: 3, c: 4}); // f(2, 3, 4);
Run Code Online (Sandbox Code Playgroud)
以下是这个想法的实现:
// Get an array of parameter names from a function
Function.parameters = function(f) {
// Find the parameter list in f.toString()
var m = /function[^\(]*\(([^\)]*)\)/.exec(f.toString());
if (!m) {
throw new TypeError("Invalid function in parameters");
}
var params = m[1].split(',');
for (var i = 0; i < params.length; i++) {
// trim possible spaces
params[i] = params[i].replace(/^\s*|\s*$/g, '');
}
return params;
};
// Convert f to a function that accepts named parameters
Function.withNamedParameters = function(f) {
var params = Function.parameters(f);
return function(args) {
var argsArray = new Array(params.length);
for (var i = 0; i < params.length; i++) {
argsArray[i] = args[params[i]];
}
return f.apply(this, argsArray);
};
};
Run Code Online (Sandbox Code Playgroud)
我有一个更灵活的实现,可以Function.withPositionalParameters在GitHub上的另一个方向():http://gist.github.com/132782.
我认为这主要用于调试目的......
详细阐述詹姆斯·韦斯特盖特(James Westgate)提出的想法,以下toString()是创建,分发和接收网络工作者的示例:
/*
* @param fun the function to carry out in the web worker
* @param mes the message to send to the web worker
* @param com the function to do on completion
* creates, dispatches & receives a web worker
*/
function wor(fun, mes, com) {
var wor = new Worker(URL.createObjectURL(new Blob([
'self.onmessage = ' + fun.toString()], {
type: 'application/javascript'
})));
wor.postMessage(mes);
wor.onmessage = com;
}
Run Code Online (Sandbox Code Playgroud)
通过将函数转换为字符串,我们可以使用它在对象URL中创建函数,然后在接收数据时对其进行解析和执行。
| 归档时间: |
|
| 查看次数: |
12004 次 |
| 最近记录: |