Javascript 调用存储在变量中的方法,而不指定此

Javascript 调用存储在变量中的方法,而不指定此,javascript,function,methods,this,method-call,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)抛出未捕获的类型错误:无法读取未定义的属性“num” bar.call(foo,3)日志3 有没有一

考虑以下代码

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)抛出未捕获的类型错误:无法读取未定义的属性“num”

bar.call(foo,3)日志
3

有没有一种方法可以将函数
foo.bar
存储在变量中,这样就可以在不指定
this
对象的情况下调用它

我知道下面的方法行得通

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

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

是的,确实存在!您可以使用
.bind()
。下面是一个例子:

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

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

bar(2);

是的,有!您可以使用
.bind()
。下面是一个例子:

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

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

bar(2);

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

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

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

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

MDN:为什么不使用
bind
指定
this
?这是最干净的方法mdn:为什么不用
bind
指定
this
?这是最干净的方法