我对ES6类链接有问题。我有一个如示例中的类。我想访问baz()方法回调。我想在WorkHard类中使用该回调。我该怎么办?
class WorkHard {
constructor() {
this.value_1 = []
this.value_2 = []
}
foo(args) {
this.value_1 = args;
return this;
}
baz(cb) {
this.value_1 = null;
this.value_2 = null;
return this;
}
zoo(args) {
this.value_2 = args;
return this;
}
}
const WorkHard = new WorkHard();
WorkHard.foo('TestValue_1').baz(() => {
console.log('This is baz() method content.');
}).zoo('TestValue_2')
您在第一个参数baz处传递了回调,因此您可以这样调用它:
class WorkHard {
constructor() {
this.value_1 = []
this.value_2 = []
}
foo(args) {
this.value_1 = args;
return this;
}
baz(cb) {
this.value_1 = null;
this.value_2 = null;
cb();
return this;
}
zoo(args) {
this.value_2 = args;
return this;
}
}
const workHard = new WorkHard();
workHard
.foo('TestValue_1')
.baz(() => {
console.log('This is baz() method content.');
})
.zoo('TestValue_2');
您不会在班级内的任何地方打电话给cb
。另外,您的实例不能与该类具有相同的名称。
只需在cb
内部执行baz
。
class WorkHard {
constructor() {
this.value_1 = []
this.value_2 = []
}
foo(args) {
this.value_1 = args;
console.log('foo called');
return this;
}
baz(cb) {
this.value_1 = null;
this.value_2 = null;
cb();
return this;
}
zoo(args) {
console.log('zoo called');
this.value_2 = args;
return this;
}
}
const workHard = new WorkHard();
workHard.foo('TestValue_1').baz(() => {
console.log('This is baz() method content.');
}).zoo('TestValue_2')
如果您希望回调函数控制链接流,请记住,回调函数本身不会返回任何内容,因此您还需要返回该函数调用,而不是返回this
// inside WorkHard
baz(cb) {
this.value_1 = null;
this.value_2 = null;
return cb(this);
}
workHard.foo('TestValue_1').baz((instance) => {
console.log('Workhard visible variables are', instance);
return instance;
}).zoo('TestValue_2');