深入淺析JavaScript中的constructor_javascript技巧

來源:互聯網
上載者:User

定義和用法

constructor 屬性返回對建立此對象的數組函數的引用。

文法

object.constructor

constructor,建構函式,對這個名字,我們都不陌生,constructor始終指向建立當前對象的建構函式。

這裡有一點需要注意的是,每個函數都有一個prototype屬性,這個prototype的constructor指向這個函數,這個時候我們修改這個函數的prototype時,就發生了意外。如

function Person(name,age){this.name = name;this.age = age;}Person.prototype.getAge = function(){return this.age;}Person.prototype.getName = function(){return this.name;}var p = new Person("Nicholas",18);console.log(p.constructor); //Person(name, age)console.log(p.getAge()); //18console.log(p.getName()); //Nicholas 

但是如果是這樣:

function Person(name,age){this.name = name;this.age = age;}Person.prototype = {getName:function(){return this.name;},getAge:function(){return this.age;}}var p = new Person("Nicholas",18);console.log(p.constructor); //Object()console.log(p.getAge()); //18console.log(p.getName()); //Nicholas 

結果constructor變了。

原因就是prototype本身也是對象,上面的代碼等價於

Person.prototype = new Object({getName:function(){return this.name;},getAge:function(){return this.age;}}); 

因為constructor始終指向建立當前對象的建構函式,那麼就不難理解上面代碼p.constructor輸出的是Object了。

對於修改了prototype之後的constructor還想讓它指向Person怎麼辦呢?簡單,直接給Person.prototype.constructor賦值就可以了:

Person.prototype = {constructor:Person,getName:function(){return this.name;},getAge:function(){return this.age;}}

以上所述是小編給大家介紹的JavaScript中的constructor ,希望對大家有所協助!

聯繫我們

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