考虑以下代码。
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/