js-提前聲明和new操作符理解

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.