函数类型转换JavaScript [英] Function Typecasting JavaScript

查看:73
本文介绍了函数类型转换JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我问了一个问题

&调用元素的onclick HTML属性中定义的JavaScript函数(使用jQuery attr/prop)

我需要以编程方式访问按钮的onclick属性,该按钮具有函数调用以及参数,然后提供额外的参数&.进行函数调用(onclick=doSomething(2,4)).

但是我发现apply/call的使用也可以方便地提供额外的参数.为此,我从属性&中提取了函数名称.它以类似

的字符串形式出现

arr[1] = 'doSomething';

我尝试使用 Function Constructor 将其视为函数,但是它不起作用 (例如Function(arr[1]))为什么?

提到的解决方案 Javascript:将字符串解释为对象引用吗?可以正常工作.但是为什么不能通过函数构造函数来实现呢?

一些代码信息

 var funDef      ='doSomething'; // this is the name of real function defined in the script
 var funcName    = new Function(funDef); //expected it to return reference of function doSomething,shows function anonymous() in console

    var funcArgs    = [5,7,10];
    funcName.apply('',funcArgs); //this is the function call.

在这种情况下,函数在我替换掉之前不会被调用

    var funcName = new Function(funDef); with var funcName = eval(funDef);

谢谢.

解决方案

我在JavaScript聊天室中对此进行了讨论,从中我了解到new Function(..)构造函数需要整个函数体以我期望的方式返回引用.

函数构造函数不考虑eval编写时在脚本中编写的doSomething函数的定义.

在此情况下可能适用的其他方法是:

Javascript将变量用作对象名称

评论?

Recently I had asked a question

Extract & call JavaScript function defined in the onclick HTML attribute of an element(using jQuery attr/prop)

I needed to programmatically access the onclick attrib of a button which had a function call along with param's in it then supply an extra param & make a function call(onclick=doSomething(2,4)).

But as I figure out that the use of apply/call can also come handy to supply extra param's.For this I extracted the the function name from the attribute & it comes in a string like

arr[1] = 'doSomething';

I tried using Function Constructor to treat this as a function but it doesn't work (like Function(arr[1])) Why?

Solution mentioned Javascript: interpret string as object reference? works fine. But why it cant be achieved via the function constructor?

Some code info

 var funDef      ='doSomething'; // this is the name of real function defined in the script
 var funcName    = new Function(funDef); //expected it to return reference of function doSomething,shows function anonymous() in console

    var funcArgs    = [5,7,10];
    funcName.apply('',funcArgs); //this is the function call.

In this case function does not get called untill I replace

    var funcName = new Function(funDef); with var funcName = eval(funDef);

Thanks.

解决方案

I discussed this on the JavaScript chat room from where I understood that new Function(..) constructor needs whole function body to return reference in the way I was expecting.

The function constructor does not consider the definition of the doSomething function that is written in the script while eval does.

Other ways that could be fit in this scenarios are here:

Javascript use variable as object name

Comments?

这篇关于函数类型转换JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆