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