The front end learning scope

Source: Internet
Author: User
No.8

The existing code is as follows:
var foo = 1;
function Main () {
Alert (foo);
var foo = 2;
Alert (This.foo)
This.foo = 3;
}
1. Please give the following two ways to call the function when the alert results and explain the cause.
var m1 = Main ();
var m2 = new Main ();
2. If you want var m1 = Main () to produce a M1 that is exactly the same as the previous M2, how do I change the main function?

1, var m1=main (), the result of alert is undefined and 1, because the first time in the alert (foo), Foo in the main () function domain has not been defined, so prompt undefined, In the output This.foo, because the function execution environment at this time is the global domain, which is equivalent to Window.main (), so This=window, so this.foo=window.foo=1
When Var m2=new main (), the result of alert is undefined and undefined, the first undefined is the same as in the previous case, and the second hint is undefined because in this case a main is constructed with new ( ), so the execution environment has changed, not the global domain, but the M2, so the this=m2 at this time, therefore this.foo=m2.foo, but because M2 in This.foo is not defined at alert (this.foo), So tip undefined
2. To M1=main () the same effect as the previous M2, the main () function is modified to be function main () {alert (foo); Foo=undefined;alert (This.foo);} Can

The front end learning scope

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.