1、提前聲明:聲明變數後,js會把聲明部分提前到範圍前面。 var a=1;function aheadOfStatement(){ alert(a); var a=2;}這段代碼結果是undefined,因為函數aheadOfStatement中的聲明了變數a,並覆蓋了全域變數a,但是沒有賦值。等價於下面的代碼: var a=1;function aheadOfStatement(){ var a; alert(a); a=2;}2、new的理解 如果在一個函數前面帶上new來調用該函數,那麼將建立一個隱藏串連到該函數的prototype成員的新對象,同時this將被綁定到那個新對象上。 執行個體1:函數沒有傳回值 複製代碼function testNoReturn(){ var a=1;}var test=testNoReturn();var testWithNew=new testNoReturn();alert(test); //undefinedalert(testWithNew); //[object Object]alert(testWithNew instanceof testNoReturn); //true複製代碼執行個體2:函數返回基本類型;沒有new的,得到a的值,有new的,得到函數testWithReturn的prototype。 複製代碼function testWithReturn(){ var a=1; return a;}var test=testWithReturn();var testWithNew=new testWithReturn();alert(test); //1alert(testWithNew); //[object Object]alert(testWithNew instanceof testWithReturn); //true複製代碼執行個體3:函數返回參考型別;沒有new的,得到了Array類型的變數,有new的,也得到了Array類型的變數,而不是得到testWithReturn的prototype。 這個執行個體中,沒有new的,是建構函式的原廠模式;有new的,是建構函式的寄生建構函式模式。 複製代碼function testWithReturn(){ var a=new Array(); a=[1,2,3]; return a;}var test=testWithReturn();var testWithNew=new testWithReturn();alert(test); //[1,2,3]alert(testWithNew); //[1,2,3]alert(testWithNew instanceof testWithReturn); //falsealert(test instanceof Array); //truealert(testWithNew instanceof Array); //true//函數返回參考型別後,有沒有new,都得到的是參考型別,有了new,也不返回函數的prototype 複製代碼執行個體4:this綁定;有new的,this指向的是testWithNew。沒有this的,指向的是調用testThis的對象,在全域環境中是window。所以可以找到a變數。 複製代碼var a=1;function testThis(){ alert(this.a); this.b=2;}var test=testThis(); //1var testWithNew=new testThis();//undefinedalert(testWithNew.b);//2