《Javascript權威指南》 建構函式

來源:互聯網
上載者:User

標籤:

類和建構函式

使用new調用建構函式會建立新對象,建構函式的prototype屬性被用作新對象的原型。

//建構函式,用以初始化新建立的“範圍對象”
//沒有建立並返回對象function Range(from, to) { this.from = from; this.to = to;}Range.prototype ={ includes: function(x) { return this.from <= x && x <= this.to;}, foreach: function(f) { for (var x = Math.ceil(this.from); x <= this.to; x++) f(x); }, toString: function() { return "(" + this.from + "..." + this.to + ")"}};var r = new Range(1,3);r.include(2); //truer.foreach(alert);console.log(r.toString()); //(1...3)

Range()建構函式只不過初始化this而已,不必返回這個新建立的對象,建構函式會自動建立對象,

 

constructor屬性

函數都擁有prototype屬性,這個屬性的值是一個對象,它包含唯一一個不可枚舉屬性constructor。constructor屬性的值是一個函數對象

var F = function() {};    var p = F.prototype;      //F相關聯的原型對象var c = p.constructor;   //與原型對象相關聯的對象alert(c === F);            //true   F.prototype.constructor == F

 

對象通常繼承的constructor屬性指代它們的建構函式。

var o = new F();o.constructor === F  //true

 

《Javascript權威指南》 建構函式

聯繫我們

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