0

是否可以一次调用执行命名空间的所有功能?

经验:

var myApp = { 

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

它适用于上面的代码..

我们可以一次调用就触发 addStyle 和警告函数吗?

我尝试过/想到的:

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

这不起作用..我怎么能做这样的事情?

现场试用:http: //jsfiddle.net/C7JJM/82/

先感谢您!

4

3 回答 3

1

如果不让每个函数自调用,自动调用所有函数看起来很困难。但是使用自定义调用者,这几乎是可能的..只需在您的第一个正在工作的函数中添加另一个名为 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/

于 2014-08-25T09:07:26.987 回答
0

试试这个

    //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/

于 2014-08-25T09:15:12.477 回答
0
var myApp = { 
     e : $('.js-box'),

        addStyle : function(){
        myApp.e.css('height','400');
        },
        warn : function(){
        alert('WOOOOOoooOO');
        }  ,
    addstyleall:function(){this.addStyle();this.warn();}

};
myApp.addstyleall();
于 2014-08-25T09:15:58.323 回答