js中new建構函式的研究

來源:互聯網
上載者:User

標籤:

《javascript進階編程》裡對new操作符的解釋:

  new操作符會讓建構函式產生如下變化:

  1.       建立一個新對象;

  2.       將建構函式的範圍賦給新對象(因此this就指向了這個新對象);

  3.       執行建構函式中的代碼(為這個新對象添加屬性);

  4.       返回新對象

/*Constr:建構函式args:初始化參數*/function newOperator(Constr, args) {    var thisValue = Object.create(Constr.prototype); // 以建構函式的原型對象建立一個新對象    var result = Constr.apply(thisValue, args);//把建構函式的this指向新對象,並為新函數添加新屬性    if (typeof result === ‘object‘ && result !== null) {        return result; // 返回新對象    }    return thisValue;}

看看這段代碼的結果

var a=5;function test(){    a=0;    alert(a);    alert(this.a);    var a;    alert(a);}test();new test();0500undefined0

再看看這段代碼的結果

var a=5;function test(){    this.a=0;    alert(a);    alert(this.a);    var a;    alert(a);}test();new test();undefined0undefinedundefined0undefined

這段代碼可以解釋為定義var a;那麼a就是函數的局部變數,只能在他的使用中的物件裡面找,當執行test()時,this.a相當於window.a;當執行new test()時,this.a這相當於新對象的屬性,而a還是test函數的局部變數,跟新對象沒關係

js中new建構函式的研究

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.