Answers to a js closure question and a js closure question

Source: Internet
Author: User

Answers to a js closure question and a js closure question

In this article, I explained the js closure and finally left a problem. The Code is as follows:

<Script type = "text/javascript"> var name = "trigkit4"; var segmentFault = {name: "My SF", getNameFunc: function () {return function () {return this. name ;}}}; alert (segmentFault. getNameFunc (); // trigkit4 is displayed. </script>

The first time I saw this problem, I thought it was the pop-up My SF, but it was not. Why? Let's parse this code.

SegmentFault is an object that defines a name attribute and the getNameFunc () method. Note that segmentFault. getNameFunc () returns a function reference, so the last code can be divided:

Var test = segmentFault. getNameFunc (); alert (test (); // The result is the same

Test is a function reference, so its function body is the content returned by getNameFunc ().

function test(){return this.name;}

This makes it clear that the scope of test () is no longer the segmentFault object, but the global scope. this refers to the window and can be verified.

Alert ("test" in window); // true is displayed.

Therefore, this. name = window. name. In the global domain, the value of name is trigkit4 and so, and trigkit4 is displayed.

Original article: http://www.ido321.com/1461.html

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.