首页 > 解决方案 > yield如何作为javascript中的参数工作

问题描述

我在学习 yield 并想知道 yield 作为函数的参数时遇到了这段代码。在这个地方看起来像一个荣耀的回归

export function * throttle(func, time) {
  let timerID = null;
  function throttled(arg) {
    clearTimeout(timerID);
    timerID = setTimeout(func.bind(window, arg), time); // what does this do????
  }
  while(true) throttled(yield);
}

export class GeneratorThrottle {

  constuctor() {};

  start = () => {
    thr = throttle(console.log, 3000);
    thr.next('');
  };

  toString = () => {
    console.log(throttle);
    console.log('start =', this.start);
  };
};

标签: javascriptasync-awaityield

解决方案


使用next方法,您可以将数据作为参数传递给生成器函数。

function* logGenerator() {
  console.log(0);
  console.log(1, yield);
  console.log(2, yield);
  console.log(3, yield);
}

var gen = logGenerator();

// the first call of next executes from the start of the function
// until the first yield statement
gen.next();             // 0
gen.next('pretzel');    // 1 pretzel
gen.next('california'); // 2 california
gen.next('mayonnaise'); // 3 mayonnaise

而且func.bind(window, arg)只是用参数来称呼它的奇特方式,

wherebind方法返回一个函数...您可以thiswindow在该函数中一样访问...

例子:

function func(args) {
    console.log(this, args)
}
func.bind("this", "args")();


推荐阅读