Home > Article > Web Front-end > Javascript trap window global object_javascript skills
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! ! */