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.