简体   繁体   English

ES6 链接访问以前的方法

[英]ES6 Chaining Access Previous Method

I have a problem with ES6 Class Chaining.我对 ES6 类链接有疑问。 I have a class as in the example.我有一个例子中的课程。 I want to access baz() method callback.我想访问 baz() 方法回调。 I want to use that callback inside WorkHard class.我想在 WorkHard 类中使用该回调。 How can I do that?我怎样才能做到这一点?

 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')

You pass callback at first argument baz, so you can call it like this: 您在第一个参数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'); 

You're not calling cb anywhere inside your class.您不会在班级内的任何地方打电话给cb Also, your instance cannot have the same name as the class.此外,您的实例不能与类同名。

Just execute cb inside baz .只需在baz中执行cb即可。

 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')

If you want the callback to control the chaining flow, keep in mind a callback returns nothing by itself, so you would need to also return that function call instead of this如果您希望回调控制链接流程,请记住回调本身不返回任何内容,因此您还需要返回该函数调用而不是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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM