最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

String to function javascript - Stack Overflow

programmeradmin5浏览0评论

Say i am using some of the html5 data chars and i want to know what function to call when say something is pleted for a certain div tag.

so my data would look like

data-callback='jsAPI.aSubset.desiredFunction'

How would i convert that callback (a string) into the function that i want to call. A simple global function such as

data-callback='_myfunction'

<script>
    function _myfunction() { alert("yes my function"); }
    $("div").click(function() {
        var fn = $(this).data("callback");
        if (typeof fn === 'function') {
            fn();
        }
    })
</script>

but how do i do it with the previous one jsAPI.aSubset.desiredFunction Thanks

Say i am using some of the html5 data chars and i want to know what function to call when say something is pleted for a certain div tag.

so my data would look like

data-callback='jsAPI.aSubset.desiredFunction'

How would i convert that callback (a string) into the function that i want to call. A simple global function such as

data-callback='_myfunction'

<script>
    function _myfunction() { alert("yes my function"); }
    $("div").click(function() {
        var fn = $(this).data("callback");
        if (typeof fn === 'function') {
            fn();
        }
    })
</script>

but how do i do it with the previous one jsAPI.aSubset.desiredFunction Thanks

Share Improve this question asked Jan 18, 2012 at 23:05 ThePrimeagenThePrimeagen 4,5724 gold badges34 silver badges45 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

Sounds like a great use case for the dreaded eval().

I would do something like:

var fnString = "jsAPI.aSubset.desiredFunction";
var fn = eval(fnString);
if (typeof(fn) === "function") {
    fn.apply();

Using square brackets only works if you have no . chain.

Try this instead:

var elms = fn.split(".");
var curr = window;
var nxt;
while(nxt = elms.shift()) curr = curr[nxt];
curr();

Use square brackets...

jsAPI.aSubset[fn]();

so...

if (typeof jsAPI.aSubset[fn] === 'function') {
    jsAPI.aSubset[fn]();
}

You might want to just use Function("functionstring"). The Function function returns a function from a string.

Try window[fn]() if the function is defined in the global scope.

发布评论

评论列表(0)

  1. 暂无评论