javascript calling a function on window object

后端 未结 3 1732
清歌不尽
清歌不尽 2021-01-12 22:13

I have the following code and am wondering how to make the last line work. I addopted a set of api\'s that current use _view appended as it\'s namespacing convention and wou

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-12 23:03

    Using the square bracket notation you're actually asking to execute a function in window called arc.view.say_hello, and not a function in the object view (that is a property of the object arc). To be more explicit:

    window["arc.view.say_hello"] = function () { alert("hi") };
    
    window["arc.view.say_hello"](); // "hi"
    

    If you want to call a function in the way you described, you have to "resolve" the objects chain. You can create an utility function for that. Something like:

    var arc={};
    arc.view={
      say_hello: function(){
        alert("I want to say hello");
      }
    }
    function say_goodbye(){
      alert("goodbye to you");
    }
    
    function call(id) {
        var objects = id.split(".");
        var obj = this;
    
        for (var i = 0, len = objects.length; i < len && obj; i++)
            obj = obj[objects[i]];
    
        if (typeof obj === "function")
            obj();
    }
    
    call("say_goodbye");
    call("arc.view.say_hello");
    

    You could also extend the utility function to use arguments (or you could just return the reference to the function).

提交回复
热议问题