无法弄清楚如何正确地将对象的方法作为参数传递。
这是我的代码:
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
有什么方法只需要传递方法,而不需要传递方法和对象?
您还需要传递
this
上下文。在提供的示例中,方法在的上下文中被调用window
,并且window
不具有属性p1
使用
.bind()
通过上下文。bind
返回一个函数,该函数在以后执行时将具有正确的上下文集,以调用原始函数。这样你就可以保持异步回调和事件背景。[参考]
试试这个:
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));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句