Home >Web Front-end >JS Tutorial >How to implement yield in javascript_javascript skills

How to implement yield in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:17:13924browse

I didn’t expect that the code was successfully tested once.~~It’s just FF, modified to support IE. Because IE does not recognize function expressions.

Copy code The code is as follows:

var Iterator = function (fn) {
var coroutine = null;
var cofn_this = null;
var yield = function() {
coroutine.apply(cofn_this, arguments);                  // support IE.
                                          / NOTE: IE eval("function(){}") does not return a function object. >               coroutine = cofn;
              cofn_this = cothis; 🎜> Array.prototype.forEach = new Iterator(function () {
for (var i = 0; i < this.length; i ) {
                                                                                                                                                                                              . = window.alert;
var A = [1,2,3,4,5];
A.forEach(function(it){
} this.display(it)
}, this );



There is a trick:

fn = eval(fn.toString())

Used to bind the reference in fn to the current context, so that the yield in fn will refer to the yield function we defined.

Note that if you need to access other this context in the coroutine, you need to pass it to the iterator, such as example.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn