简化将匿名javascript函数绑定到类

时间:2010-01-30 00:28:10

标签: javascript prototypejs

我有一大堆javascript函数,我正在使用Prototype重构为一组类。

我想知道是否有办法让匿名函数绑定到类更简单?我一直忘记在最后添加绑定。或者这只是它一直在做的方式?

 var arr = this.getSomeArray();
 arr.each(function(t) {
     t.update(val);
     this.updateJSValue(t);
 }.bind(this));

1 个答案:

答案 0 :(得分:1)

您的选项基本上是调用某个函数(bindaddMethods或您编写的其他函数)或使用局部变量而不是this

var self=this;
arr.each(function(t) {
     t.update(val);
     self.updateJSValue(t);
});

如果你有大量的函数,那么局部变量需要的输入最少。对于一些函数来说,没有太大的区别。

function ThingMixin(self) {
    self.foo = function(arr) {
        arr.each(function(t) {
             t.update(val);
             self.updateJSValue(t);
        });
    };
    ...
};
...
ThingMixin(Ralph.prototype);

// or an anonymous function:
(function (self){
    self.foo = function(arr) {
        arr.each(function(t) {
             t.update(val);
             self.updateJSValue(t);
        });
    };
    ...
})(Ralph.prototype);