如何在 Javascript 中将对象的方法作为参数传递
How to pass object's method as a parameter in Javascript
无法弄清楚如何将对象的方法作为参数正确传递。
这是我的代码:
var MyTest = function (p1) {
this.p1 = p1;
};
MyTest.prototype.getParam = function () {
return this.p1;
};
function doAction(getParamCallback) {
console.log(getParamCallback());
}
var mt = new MyTest(123);
console.log(mt.getParam()); // 123
doAction(mt.getParam); // undefined
我发现正确传递方法的唯一方法是同时传递对象和方法并使用 call():
function doAction2(obj, getParamCallback) {
console.log(getParamCallback.call(obj));
}
doAction2(mt, mt.getParam); // 123
有什么方法只需要传递方法,而不是同时传递方法和对象吗?
You need to pass the this
context as well. In provided example, methos is being called in the context of window
, and window
does not have property p1
Use .bind()
to pass the context. bind
returns a function that when later executed will have the correct context set for calling the original function. This way you can maintain context in async callbacks, and events.[Reference]
试试这个:
var MyTest = function(p1) {
this.p1 = p1;
};
MyTest.prototype.getParam = function() {
return this.p1;
};
function doAction(getParamCallback) {
alert(getParamCallback());
}
var mt = new MyTest(123);
doAction(mt.getParam.bind(mt));
无法弄清楚如何将对象的方法作为参数正确传递。
这是我的代码:
var MyTest = function (p1) {
this.p1 = p1;
};
MyTest.prototype.getParam = function () {
return this.p1;
};
function doAction(getParamCallback) {
console.log(getParamCallback());
}
var mt = new MyTest(123);
console.log(mt.getParam()); // 123
doAction(mt.getParam); // undefined
我发现正确传递方法的唯一方法是同时传递对象和方法并使用 call():
function doAction2(obj, getParamCallback) {
console.log(getParamCallback.call(obj));
}
doAction2(mt, mt.getParam); // 123
有什么方法只需要传递方法,而不是同时传递方法和对象吗?
You need to pass the
this
context as well. In provided example, methos is being called in the context ofwindow
, andwindow
does not have propertyp1
Use
.bind()
to pass the context.bind
returns a function that when later executed will have the correct context set for calling the original function. This way you can maintain context in async callbacks, and events.[Reference]
试试这个:
var MyTest = function(p1) {
this.p1 = p1;
};
MyTest.prototype.getParam = function() {
return this.p1;
};
function doAction(getParamCallback) {
alert(getParamCallback());
}
var mt = new MyTest(123);
doAction(mt.getParam.bind(mt));