从另一个外部函数调用mootools类方法

时间:2013-03-20 22:05:38

标签: javascript class mootools

我有一个我正在使用的具有许多功能的传统mootools类。我试图简单地从类外部调用一个类方法,而不是扩展类。所以,如果班级看起来像这样:

var myClass = new Class({
    search: function(){
        this.searchSpinner.show();
        this.request.send({data: this.data});
    },

    // many other functions
})

我需要从同一页面上加载的另一个脚本中调用search方法。

现在我正在尝试这样:

window.myClass.search();

但是这导致了一个很大的错误,我无法理解,但看起来像是:

Uncaught TypeError: Object function (){e(this);if(g.$prototyping){return this;}this.$caller=null;var i=(this.initialize)?this.initialize.apply(this,arguments):this;this.$caller=this.caller=null;
return i;} has no method 'search' 

有没有'正确'的方法来调用此方法?

2 个答案:

答案 0 :(得分:3)

使用Mootool Class定义的类在其他语言中的行为与静态类不同。为了访问该类中的方法,您必须首先创建该类的实例:

var classObj = new myClass(/*any parameters if required, check the "initialize" method*/);
classObj.search();

答案 1 :(得分:1)

您正在尝试应用“单例”模式:如果您只使用此类的一次出现,则可以使用:

var mySingleton = new new Class({

(注意2 x new关键字)然后

mySingleton.search()

称呼它......

哦,如果你试图将静态函数添加到mootools类,只需将它们声明为:

var myClass = new Class({ });
myClass.staticMethod = function() {
    // ...
};

希望这有帮助!