JavaScript to implement yield method _javascript skills

Source: Internet
Author: User

I didn't expect the code to test successfully. ~ ~ is only ff below, modified to support IE. Because IE does not recognize function expressions.

Copy Code code 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.
Eval (' fn = ' + fn.tostring ());
return function (Cofn, cothis) {
Coroutine = cofn;
Cofn_this = Cothis;
Return Fn.apply (This)
};
}
Array.prototype.forEach = new iterator (function () {
for (var i = 0; i < this.length i + +) {
Yield (This[i])
}
});
Example.
This.display = Window.alert;
var A = [1,2,3,4,5];
A.foreach (function (IT) {
This.display (IT)
}, this);

One of the tips is:

fn = eval (fn.tostring ())

Used to bind a reference in FN to the current context so that the yield in FN references the yield function we defined.

Note that if you need to access the other this context in coroutine, you need to pass it in to iterator, such as example.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.