function Fun(argument1,argument2){
return this;
}
//直接調用
var f1 = Fun(); // window {}
//實例化對象
var f2 = new Fun(); // Fun {}
f1 只是調用 Fun函數,而 f2是實例化對象 Fun锰霜。兩個的this指向的不是同個地方行施。調用函數的this指向的是window,實例化對象的this指向的是對象本身田弥。
(構造函數的命名通常使用駝峰命名法履磨,首字母大寫税朴,以此和普通的函數區(qū)分開來宰啦,這是一種習慣用法肴颊。)
測試例子:
function fun1(){
//沒有實例化fun1(), 直接調用,這里的this指的是window對象
console.log(this);
function fun2(){
//沒有實例化fun2(), 直接調用供填,這里的this指的是window對象
console.log(this);
}
fun2();
function fun3(){
//a實例化fun3(), 這里的this指的是對象本身
console.log(this);
}
var a = new fun3();
}
var f = fun1();
//輸出的結果如下
>> window {}
>> window {}
>> fun3 {}
如上拐云,f只是調用fun1,輸出的第一個this是指向window的。fun2也只是調用近她,所以this也是指向windowde叉瘩。a是實例化的對象,this指向的是fun3實例化后的對象粘捎。
如果做下面調整薇缅。
function fun1(){
// f 實例化fun1(), 這里的this指的是fun1對象本身
console.log(this);
function fun2(){
//沒有實例化fun2(), 直接調用,這里的this指的是window對象
console.log(this);
}
fun2();
function fun3(){
//a實例化fun3(), 這里的this指的是對象本身
console.log(this);
}
var a = new fun3();
}
var f = new fun1();
//輸出的結果如下
>> fun1 {}
>> window {}
>> fun3 {}
如上攒磨,fun1跟fun3是被實例化捅暴,this指向對象本身,fun2只是調用咧纠,this指向window。
那給this的屬性賦值會有什么樣的結果呢泻骤?
this.alia = 'window';
this.win1 = 'window property'
function fun1(){
this.alia = 'fun1';
this.ofun1 ="only fun1 have"
console.log("fun1的alia : " + this.alia); //"fun1的alia :fun1"
console.log(this.win1); // "window property"
function fun2 (){
this.alia = 'fun2';
console.log("fun2的alia :" + this.alia); //"fun2的alia :fun2"
console.log(this.ofun1); // "only fun1 have"
console.log(this.win1); // "window property"
this.ofun1 = "fun2 change"
}
fun2();
console.log("this.ofun1 :" +this.ofun1 ); //this.ofun1 :fun2 change
}
fun1();
調用函數里面的this屬性賦值都是給window賦值的漆羔。
如果 fun1()改成 var a = new fun1(); 呢?
this.alia = 'window';
this.win1 = 'window property';
var a = new fun1();
function fun1(){
//fun1內的this指的是 a 對象狱掂,是fun1{};
this.alia = 'fun1';
this.ofun1 ="only fun1 have"
console.log("fun1的alia : " + this.alia); //"fun1的alia :fun1"
console.log(this.win1); // "undefine"
function fun2 (){
// this指的是window演痒。
//window沒有ofun1屬性,所以輸出了undefine
console.log(this.ofun1); // "undefine"
//下面都是window已有的屬性
console.log("fun2的alia :" + this.alia); //"fun2的alia :window"
console.log(this.win1); // "window property"
//給window添加ofun1屬性
this.ofun1 = "change in fun2"
}
fun2();
// 這時this 是 a對象本身的fun1{}
console.log("this.ofun1 :" +this.ofun1 ); //this.ofun1 :only fun1 have
//window.ofun1剛剛已經在fun2里面賦值了,所以輸出有值
console.log("window.ofun1 :" +window.ofun1 ); //window.ofun1 :change in fun2
}
大家仔細看看輸出的結果趋惨。