Scope of variables in Javascript constructor, javascript Constructor

Source: Internet
Author: User
Tags variable scope

Scope of variables in Javascript constructor, javascript Constructor

Constructor can be used with new to create objects. It can also be called as a common function because it is also a function.

function Person(name) {this.name=name;}Person(12);alert(window.name);//12

 

This indicates the global window object when the constructor is called as a common function. It is obvious that the constructor is treated as a common function call. It is not a good practice and there is no reason to do so. In practice, we should avoid such strange usage to avoid strange problems.

 

function Person(name,sex) {    this.name=name;    var name1="22";    name2=sex;}var per = new Person("aty","boy");alert(per.name);// atyalert(per.name1);//undefinedalert(per.name2);//undefinedalert(window.name2);//boy

 

The constructors define variables using this as member variables; var as local variables; without a keyword, this variable is added to the window object. This explains why the this keyword is used in constructors.


JavaScript variable scope Problems

Function is not implemented,

However, your code is not a scope issue,
You set var targetImage = document. getElementById ('floatingimg ');
Put this sentence outside the floating method, that is, the page will be executed as soon as it is loaded, at this time, the id = "'floatingimg '" element has not been loaded (even the <body> element does not exist), of course, it is empty.
Put this code in window. onload = function () {};

A Javascript variable scope

Because in the second example, before you call test (), the sentence "document. write ("<LI>" + langVBS); "An error occurred (" langVBS undefined "). Therefore, the test () function is not called and only" document. write ("<LI>" + langJS.
In the first example, this error occurs only after test () is called, so the execution of the text () function is not affected.

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.