传递属于对象的匿名方法作为参数-Javascript
Pass anonymous method belonging to object as an argument- Javascript
我有一个带有方法的对象,我想将该方法作为参数传递给另一个函数。但是,函数必须知道与方法关联的对象(否则在创建后无法访问分配给对象的值)。
有没有一种方法可以做到这一点,而不需要将对象/方法作为字符串传递
(不使用除外:window[function_name];
)
function My_Object(name){
this.name = name;
}
My_Object.prototype.My_Method = function(){
alert(this.name);
}
//This is the function that passes the method
function Runner(){
var NewObject = new My_Object('Andre');
test(NewObject.My_Method);//this is where it should break
}
//This is the function that receives and calls the Object's method
function test(func){
func();
}
使用匿名函数:
//This is the function that passes the method
function Runner(){
var NewObject = new My_Object('Andre');
test(function() {
NewObject.My_Method();
});
}
或者将您的方法绑定到NewObject
,如下所示:
//This is the function that passes the method
function Runner(){
var NewObject = new My_Object('Andre');
test(NewObject.My_Method.bind(NewObject));
}
如果您将来不更改test
函数,您可以简单地调用Runner
函数中要测试的函数:
//This is the function that passes the method
function Runner(){
var NewObject = new My_Object('Andre');
NewObject.My_Method(); // directly call the function
}
关于执行上下文的注释在这里很重要:
//This is the function that passes the method
function Runner(){
var NewObject = new My_Object('Andre');
test(NewObject.My_Method,NewObject);
}
//This is the function that receives and calls the Object's method
function test(func,ctx){
func.apply(ctx || this);
}
相关文章:
- 如何确保函数/方法参数为certian类型
- 我怎么能读“;.on()"jQuery中的方法参数
- Javascript 方法参数转义
- 对象属性来自方法参数时未定义
- 在 c# 中将多维 JavaScript 数组绑定为方法参数
- 如何通过javascript获取post()方法参数
- AngularJS$http://.NET Web API-获取400(错误请求)或NULL POST操作方法参数
- _.chain()中的方法参数
- springmvc:如何在没有控制器方法参数的情况下以mvc传递参数
- JSON作为null传递给方法参数
- Javascript,可以在没有 eval 的情况下传递未声明的方法参数
- 单词“in”是什么意思?在文档中的方法参数列表中
- 如何返回对象方法参数
- 实例变量vs方法参数
- 如何传递Json字符串作为javascript方法参数
- 将方法参数/参数传递给方法引用绑定,匿名,命名
- 不合逻辑的Passport验证方法参数
- 调试javascript方法参数
- 如何使用javascript获取方法参数的值
- Javascript在字符串模板中插入方法参数