如何一次触发多个名称空间函数

How to fire multiple namespace functions at once?

本文关键字:空间 函数 何一次      更新时间:2023-09-26

是否有可能在一次调用中执行名称空间的所有功能?

Exp:

var myApp = { 
    e : $('.js-box'),
    addStyle : function(){
    myApp.e.css('height','200');
    },
    warn : function(){
    alert('WOOOOOoooOO');
    }  
};
myApp.addStyle();
myApp.warn();

上面的代码可以正常工作…

我们可以用一次调用来触发addStyle和warn函数吗?

我试过/想过的:

var myApp = { 
    workAll : function(){
        e : $('.js-box'),
        addStyle : function(){
        myApp.e.css('height','200');
        },
        warn : function(){
        alert('WOOOOOoooOO');
        }
    }    
};
myApp.workAll();

this不起任何作用…我怎么能做那样的事?

Live try: http://jsfiddle.net/C7JJM/82/

提前感谢!

如果不让每个函数都自调用,自动调用所有函数看起来很困难。但是使用自定义调用者,这是非常可能的…只要在你的第一个正在工作的函数中添加另一个名为workAll的函数。

var myApp = { 
        e : $('.js-box'),
        addStyle : function(){
            console.log("Add style called");
            myApp.e.css('height','200');
        },
        warn : function(){
            alert('WOOOOOoooOO!!!');
        },
        runAll : function(){
            this.addStyle(); //call AddStyle
            this.warn(); //call Warn
        }
};
myApp.runAll();

此处演示:

http://jsfiddle.net/C7JJM/84/

试试这个

    //http://stackoverflow.com/questions/5999998/how-can-i-check-if-a-javascript-variable-is-function-type
    function isFunction(functionToCheck) {
     var getType = {};
     return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
    }
    function executeAll(ns){
        if(ns){
        for (property in ns) {
                if (ns.hasOwnProperty(property)) {
                    var p = ns[property];
                    if (p != null && isFunction(p)) {
                        p();
                    }
                }
            }
        }
    }
   var myApp = { 
            e : $('.js-box'),
            addStyle : function(){
            myApp.e.css('height','200');
            },
            warn : function(){
            alert('WOOOOOoooOO');
                }  
    };
    executeAll(myApp)

但是要注意传递给函数

的实参http://jsfiddle.net/s8ng608f/1/

var myApp = { 
     e : $('.js-box'),
        addStyle : function(){
        myApp.e.css('height','400');
        },
        warn : function(){
        alert('WOOOOOoooOO');
        }  ,
    addstyleall:function(){this.addStyle();this.warn();}
};
myApp.addstyleall();