javascript - 调用存储在变量中的方法而不指定 this

标签 javascript function methods this method-call

考虑以下代码。

class Foo {
  num = 0;
  bar = function(arg) {
    console.log(this.num + arg);
  }
}

const foo = new Foo();
const bar = foo.bar;

foo.bar(1);

bar(2);

bar.call(foo, 3);

foo.bar(1);日志1 .

bar(2);抛出Uncaught TypeError: Cannot read property 'num' of undefined .

bar.call(foo, 3);日志3 .

有没有办法存储函数foo.bar以这样的方式在变量中调用它,而无需指定 this对象?

我知道以下内容会起作用。

const foobar = function(arg) {
  foo.bar(arg);
}

有没有办法避免创建中间函数?我想将方法​​作为参数传递给另一个函数,并且必须创建大量中间函数确实会降低代码的可读性。

最佳答案

用箭头函数定义字段;这将使 this 引用该实例:

bar = (arg) => {
  console.log(this.num + arg);
}

关于javascript - 调用存储在变量中的方法而不指定 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55328969/

相关文章:

javascript - Deferred 和/或 Promise 数组的 jQuery.when() 进度

C语言,段错误在哪里?

function - 您从 Rebol2 中的对象/函数上的 THIRD 获得的未记录 block 是什么?

Ruby 哈希类方法 has_key? vs方法成员?

python - python中如何传入另一个相同类型的对象作为方法参数?

java - 是否可以在运行时将方法调用重定向到同一对象的另一个实例?

javascript - 如何等待另一家商店在一家商店发生的发货

javascript - 挂接到 insertElement 事件是否安全?

JavaScript 在不同时间执行相同的函数

javascript - React-navigation 切换主题切换