我如何传递一个对象的方法作为参数没有对象
How do I pass an objects method as parameter without the object
那么,我有一种情况,我需要调用我的对象的一个方法,但在我调用它的时候,对象和被调用的方法都可能不同。
var myCallback = "nameOfMethod"; //this can change throughout
function myObj(){
this.method1 = function(){//code};
this.method2 = function(){//more code};
}
var o1 = new myObj();
var o2 = new myObj();
//this is what i'm not sure how to do, but effectively...
//where myCallback could be method1 or method2
//and someObject could be o1 or o2 (for example)
doSomething(someObject,myCallback);
function doSomething(anObj, aMethod){
anObj.aMethod();
//or this
aMethod.call(anObj);
}
编辑:好吧。为了澄清问题。在method1和method2中,它引用了使用this
的对象的其他属性,即this。myProperty……但是当我在doSomething中使用anObj[aMethod]()
调用方法时,它返回这个。
如果我的对象如下,例如:
function myObj(){
this.myProperty = "value";
this.method1 = function(){
console.log(this.myProperty);
};
this.method2 = function(){/* more code */};
}
var o1 = new myObj();
var o2 = new myObj();
//this is what i'm not sure how to do, but effectively...
//where myCallback could be method1 or method2
//and someObject could be o1 or o2 (for example)
doSomething(someObject,myCallback);
function doSomething(anObj, aMethod){
anObj[aMethod]();
}
正确的调用方法是
anObj[aMethod]();
你的问题是,aMethod
是一个属性的名称,而不是一个函数本身。anObj[aMethod]
通过读取对象的属性将名称转换为函数。
也就是说,在JavaScript中,当您可以直接传递函数时,将回调作为两个单独的值传递是不太常见的。
相关文章:
- 我们可以用参数对象集合而不是原始数据来调用JavaScript collection.reduce()方法吗
- 如何将参数对象传输到函数
- 为什么参数对象没有在控制台中显示它的方法
- JavaScript参数对象不起作用
- 如何在 JavaScript 中取消移位或添加到参数对象的开头
- 使用参数对象而不是参数
- JavaScript 参数对象 MDN 指南
- 如何获取参数对象的子集?(关于具有可变大小的参数)
- 如何更好地检查 javascript 中的参数对象
- 如何使用 ajax 调用带有参数(对象)的服务器端方法,其中 url 具有查询参数
- 如何在 ie8 中检测参数对象
- 手动将 AngularJS $http参数对象转换为 URL 参数
- JavaScript 参数对象引用未知
- Javascript - 对 2 参数对象的数组进行排序
- 为什么下划线说 _.initial 对参数对象特别有用
- 未命名的传递参数不包含在“参数”对象中
- JavaScript:获取回调的参数对象
- Javascript参数对象
- 围绕JavaScript参数对象使用的Sonar违规
- each()在IE8上不起作用,并给了我一个“;期望应用数组或参数对象”;.如何解决