我想通过将方法从类解析为函数来向数组添加值。
班级:
class Foo {
constructor() {
this.arr = [];
}
add(value) {
this.arr.push(value);
}
}
用法:
let foo = new Foo();
a(foo.add, "a String");
function a(func, value) {
func(value);
}
答案 0 :(得分:1)
您的add
函数未绑定到您的对象,这意味着this
变量取决于它的上下文。
如果愿意
constructor() {
this.arr = [];
this.add = this.add.bind(this);
}
它将替换未绑定到新对象的添加,无论您在何处调用它,它都将引用该实例。
或者在ES6中,您可以执行此操作,这与我之前的示例具有相同的绑定力,但是在后台。
add = (value) => {
this.arr.push(value);
}
答案 1 :(得分:1)
在构造函数中,您需要将add函数绑定到该类。
this.add = this.add.bind(this);
此外,您还需要引用arr变量。
this.arr.push
保留Foo实例的上下文。
答案 2 :(得分:0)
使用箭头功能来防止自动绑定add = (value) => {...}