如何在Javascript中将对象的方法作为参数传递(How to pass object's method as a parameter in Javascript)

编程入门 行业动态 更新时间:2024-10-14 18:17:37
如何在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

有没有办法只需要传递方法,而不是方法和对象?

Can't figure out how to pass object's method as a parameter properly.

Here is my code:

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

The only way to pass a method correctly I have found is to pass both object and method and use call():

function doAction2(obj, getParamCallback) { console.log(getParamCallback.call(obj)); } doAction2(mt, mt.getParam); // 123

Is there any way that requires only method to be passed, not both method and object?

最满意答案

您还需要传递this上下文。 在提供的示例中,在window的上下文中调用methos,并且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)); 
  
 

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]

Try this:

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)); 
  
 

更多推荐

本文发布于:2023-08-03 23:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405313.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   对象   参数   方法   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!