gpt4 book ai didi

javascript - 将属于对象的匿名方法作为参数传递 - Javascript

转载 作者:行者123 更新时间:2023-11-29 19:34:23 25 4
gpt4 key购买 nike

我有一个带有方法的对象,我想将该方法作为参数传递给另一个函数。但是,该函数必须知道与该方法关联的对象(否则它无法访问创建后分配给该对象的值)。

有没有办法不用将对象/方法作为字符串传递?
(例如不使用: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();
});
}

像这样将您的方法绑定(bind)到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
}

关于javascript - 将属于对象的匿名方法作为参数传递 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25896240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com