2013-04-09 61 views
2
var x = (arg1, arg2) { 
    this.y = arg1; 
    this.z = arg2; 
} 

x.prototype.a = function() { 
    var self = this; 
    some_obj1.on('data', function() { 
    self.y = 'new y value'; 
    }); 
} 

x.prototype.b = function() { 
    var self = this; 
    some_obj2.on('data', function() { 
    self.z = 'new z value'; 
    }); 
} 

是否有任何方法将自己声明为实例变量(显然不使用'this'),以便它不需要在每个函数中声明?因此,例如申报“一”是:JavaScript对象原型此参考

x.prototype.a = function() { 
    ob2.on('data', function() { 
    self.z = 'some new value'; 
    }); 
} 

希望这个例子是非常明显的,这不是测试(问这个问题的时候写上飞)多的伪代码,但应该传达出点。

回答

2

不,你不能。您需要以某种方式修改范围链,以避免使用this。稍微更简洁的方法是使用Function#bind来指定this

x.prototype.a = function() { 
    ob2.on('data', function() { 
    this.z = 'some new value'; 
    }.bind(this)); 
} 
2

最好的办法是部分应用参数。以下是较新的Function.prototype.bind的跨浏览器实现。 project.bind使用以下实现,如果可用则使用本地Function.prototype.bind;如果本地不可用,则使用自定义实现。

更新 我创建了一个工作Fiddle。现在

project = {}; 
project.bindJs_ = function(fn, selfObj, var_args) { 
    if (!fn) { 
    throw new Error(); 
    } 

    if (arguments.length > 2) { 
    var boundArgs = Array.prototype.slice.call(arguments, 2); 
    return function() { 
     // Prepend the bound arguments to the current arguments. 
     var newArgs = Array.prototype.slice.call(arguments); 
     Array.prototype.unshift.apply(newArgs, boundArgs); 
     return fn.apply(selfObj, newArgs); 
    }; 

    } else { 
    return function() { 
     return fn.apply(selfObj, arguments); 
    }; 
    } 
}; 
// A router for the native Function.prototype.bind 
project.bindNative_ = function(fn, selfObj, var_args) { 
    return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments)); 
}; 



    project.bind = function() { 
     if (Function.prototype.bind && 
      Function.prototype.bind.toString().indexOf('native code') != -1) { 
      project.bind = project.bindNative_; 
     } else { 
      project.bind = project.bindJs_; 
     } 
     return project.bind.apply(null, arguments); 
    }; 

你可以这样做:

x.prototype.a = function() { 
    ob2.on('data', project.bind(function() { 
    // the this. object inside the function will now point to x. 
    this.z = 'some new value'; 
    }, this, any, argument, you, want, to, pass)); 
} 
+0

您发布的代码已损坏... goog来自哪里? – Dennis 2013-04-09 11:23:29

+0

无法正确选中两个答案,但这个答案也是正确和有效的。谢谢你的帮助! – gratz 2013-04-10 12:08:30