zoukankan      html  css  js  c++  java
  • 模拟es6的generator

    //es6 

       

    function* letters() {
      console.log('a');
      yield 'a';
      console.log('b');
      yield 'b';
      while (true) {
        console.log('c');
        yield 'c';
      }
    }
    

     //polyfilling es5

      

    function letters() {
      var state = 0;
      return {
        next: function() {
          switch (state) {
            case 0:
              console.log('a');
              state = 1;
              return {
                value: 'a', // Return the first yielded value.
                done: false
              };
            case 1:
              console.log('b');
              state = 2;
              return {
                value: 'b', // Return the second yielded value.
                done: false
              };
            case 2:
              console.log('c');
              return {
                value: 'c', // Return the third yielded value... forever.
                done: false
              };
          }
        }
      };
    }
    

      简述:上述方法只是 通过肉眼观察原函数 的内部代码 来编写polyfilling 的代码,可以从原函数的3个yield和polyfilling之后的3个case可以看出,

           故猜想:真正的polyfill应该是代码根据原函数生成yield,先将原函数toString,用正则匹配来分析yield, 对于原函数里面的循环(for while ....),应对应生成迭代器

          上述猜想待完善中......

         代码搬运至  https://gu.illau.me/posts/polyfilling-generators/

  • 相关阅读:
    为什么要对url进行encode
    活在当下
    Linux Shell 文本处理工具
    Servlet、Servlet容器等内容讲解
    Java编程中的一些常见问题汇总
    创建文件目录
    ubuntu
    iptables
    mysqldump导入导出
    pt-table-sync
  • 原文地址:https://www.cnblogs.com/tony-stark/p/12950808.html
Copyright © 2011-2022 走看看