【问题标题】:How does yield work as a argument in javascriptyield如何作为javascript中的参数工作
【发布时间】:2021-11-01 21:39:01
【问题描述】:

我在学习 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);
  };
};

【问题讨论】:

标签: javascript async-await yield


【解决方案1】:

使用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) 只是用参数调用它的奇特方式,

其中bind 方法返回一个函数... 您可以在该函数中以window 的身份访问this...

例子:

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

【讨论】:

    猜你喜欢
    • 2019-04-27
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多