开发者

calling inner-function dynamically in javascript

is it possible to call inner function dynamically(by it's name)?

e.g.

function a()开发者_开发问答{
    function b(){..}
    var funcName = "b";
    //calling the function b somehow using funcName
}

I know it's possible by using eval, but I rather not using eval, if b was global function I could use window[funcName] or global[funcName]...


Sounds like you want to access b through its name ("b") magically, without recording the name b in a separate structure.

You are correct that global variables are properties of the global object, generally accessed through the identifier window in web environments. It's fun how that works actually, as window is a property of the global object pointing to itself, but, that is off topic.

Local variables are properties of an object, too -- the call object. This object exists temporarily during the call. If you could get to the call object directly, then you would be able to say something like theCallObject[funcName], because the nested function is still a local variable, although hoisted. Alas, this object is not directly accessible, so you basically have to revert to the techniques shown in the earlier answers.

Here is an SO question with info: How to output call object in javascript?.

I suppose it is possible to write a JS engine with an extension permitting access to the call object, much like Mozilla gave us the non-standard __proto__.


Well, if you can declare it differently, and it's not so hard:

function a(){
    this.b = function() {...};

    // dynamic access
    var funcName = "b";
    this[funcName]();

    // still need static access?
    var b = this.b;
    b();
}

You can mix it up, of course. But Functions are just objects (both a and b), so they can be assigned, moved around, and even have instance members.


A variation on OverZealous's answer that does not muck with this:

function a(){
    function b(){..}
    var internalFuncs = {"b": b}
    var funcName = "b"
    internalFuncs[funcName]()
}

Happy coding.


Another approach:

var a = (function() {
    return {
        b: function() { alert("b"); },
        c: function() { alert("c"); },
        d: function() { alert("d"); }
    }
})();

a["b"]();

Fiddle: http://jsfiddle.net/raSKW/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜