在下面的例子中,基于一些条件,我应该从我的类中调用foo方法或从alternative.js中调用foo方法;我在myFunc变量中分配方法并调用那个变量但是如果我想调用myClass的foo方法,它就会失效因为name在myClass。prototype。myClass中没有定义。有什么解决办法吗?如果你需要更多的说明,请告诉我:
MyClass.prototype.test = function(name) {
var myClass;
var myFunc;
shouldWork = true;
if(shouldWork){
p = require('alternative.js')
myFunc = p['foo'];
}else{
myClass= this.myclass(name);
myFunc = myClass['foo'];
}
myFunc('bar');// if "shouldWork" is true it works, but if it is false, it fails
//In other words, myClass.foo('bar') works but calling
//the variable which is set to myClass['foo']
}
MyClass.prototype.myclass = function(name) {
// Here I do some operations on name and if it is undefined it breaks!
// name gets undefined if you foo method of myClass if you have it in
//a variable, becuse it is not assiging name which is from prototype
}
您可以使用.bind()
将对象绑定到方法调用。例如,如果您试图将特定对象的方法保存到myFunc
中,那么您可以这样做:
myFunc = myClass.foo.bind(myClass);
然后,当你以后这样做的时候:
myFunc(...);
它实际上会使用对象引用myClass
来正确地将其作为方法调用。
详细信息请参见.bind()的MDN参考。