Home > Web Front-end > JS Tutorial > body text

Javascript trap window global object_javascript skills

WBOY
Release: 2016-05-16 18:58:13
Original
992 people have browsed it

function Test(){
this.name='Test';
var name=2;
this.show=function(){
alert(name);
alert(this. name);//Display name
}
}
var test=new Test();//Create an object through the constructor
test.show();//Output 2 and 'Test ' , indicating that object methods must add this when accessing their properties.

function Test2(){
this.name='Test2';
this.show=function(){
alert (name);
alert(this.name);
}
}
Test();//Directly call Test();
var test2=new Test2();
test2.show();//Test and Test2 are output. It’s very strange. What is the value of name? And why is it ‘Test’, bug?
alert(name);
window.show (); //Output 2, test; Why is there a show function? Is it a bug?

//Output 2, Test; Test, Test2; Test; 2, Test

/ / The running results are the same under both ff and ie6. It doesn’t seem to be a bug. So why?
// Note: When an object method accesses the properties of its object | it must | add this. (different from java).
// The entire page defaults to the |window| object, so the defined function, The default is the method of the window object.
//When calling a function directly, it is equivalent to calling a method through window., then this inside the method is naturally
//window object, this.name='Test' adds an attribute to the window object.
// Then when name is not defined in the local scope of the method and calling alert(name), it is equivalent to calling alert(window.name);
/*Ah, the code is confusing. This looks like a serious trap! ! */

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!