JavaScript中的prototype和constructor簡明總結

來源:互聯網
上載者:User

 一直沒弄清楚JavaScript中的prototype和constructor屬性,今天看了看書,總算有點眉目了

一、constructorconstructor的值是一個函數。在JavaScript中,除了null和undefined外的類型的值、數組、函數以及對象,都有一個constructor屬性,constructor屬性的值是這個值、數組、函數或者對象的建構函式。如: 代碼如下:var a = 12, // 數字    b = 'str', // 字串    c = false, // 布爾值    d = [1, 'd', function() { return 5; }], // 數組    e = { name: 'e' }, // 對象    f = function() { return 'function'; }; // 函數 console.log('a: ', a.constructor); // Number()console.log('b: ', b.constructor); // String()console.log('c: ', c.constructor); // Boolean()console.log('d: ', d.constructor); // Array()console.log('e: ', e.constructor); // Object()console.log('f: ', f.constructor); // Function()  以上的建構函式都是JavaScript內建的,我們也可以自訂建構函式,如:  代碼如下:function A(name) {    this.name = name;} var a = new A('a'); console.log(a.constructor); // A(name)  調用建構函式時,需要用new關鍵字,建構函式返回的是一個對象,看下面的代碼就知道了: 代碼如下:var a = 4;var b = new Number(4); console.log('a: ', typeof a); // a: numberconsole.log('b: ', typeof b); // b: object  二、 prototypeprototype是函數的一個屬性,預設情況下,一個函數的prototype屬性的值是一個與函數同名的Null 物件,匿名函數的prototype屬性名稱為Object。如:  代碼如下:function fn() {} console.log(fn.prototype); // fn { }  prototype屬性主要用來實現JavaScript中的繼承,如: 代碼如下:function A(name) {    this.name = name;} A.prototype.show = function() {    console.log(this.name);}; function B(name) {    this.name = name;} B.prototype = A.prototype; var test = new B('test'); test.show(); // test  這兒有一個問題,test的建構函式其實是A函數而不是B函數:  代碼如下:console.log(test.constructor); // A(name) 這是因為B.prototype = A.prototype把B.prototype的建構函式改成了A,所以需要還原B.prototype的建構函式: 代碼如下:function A(name) {    this.name = name;} A.prototype.show = function() {    console.log(this.name);}; function B(name) {    this.name = name;} B.prototype = A.prototype;B.prototype.constructor = B; var test = new B('test'); test.show(); // testconsole.log(test.constructor); // B(name)  之所以要這麼做,是因為prototype的值是一個對象,且它的建構函式也就是它的constructor屬性的值就是它所在的函數,即: 代碼如下:console.log(A.prototype.constructor === A); // true 

聯繫我們

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