Home > Web Front-end > JS Tutorial > body text

How to implement yield in javascript_javascript skills

WBOY
Release: 2016-05-16 17:17:13
Original
858 people have browsed it

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.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!