標籤:
類和建構函式
使用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權威指南》 建構函式