// 使用inherited函數創建對象 這個對象繼承原型對象中
function inherit(p) {
if (p== null) throw TypeError();
if (Object.create)
return Object.create(p);
var t = typeof p;
if (t != "object" && t != "function") throw TypeError();
function f() {};
f.prototype = p;
return new f();
};
// 這個工廠方法返回一個心得"范圍對象"
function range (from, to) {
var r = inherit(range.methods);
// 儲存心得”范圍對象“ 得其實位置和結束位置
// 這兩個屬性是不可繼承得, 沒個對象都擁有唯一得屬性
r.from = from;
r.to = to;
// 返回這個創建得新對象
return r;
}
// 原型對象定義方法,這些方法為每個范圍對象所繼承
range.methods = {
includes: function (x) {
return this.from <= x && x <= this.to;
},
// 對於范圍內得每個整數都調用一次f
// 這個方法只可用做數字范圍。
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 = range(1, 3); //創建一個范圍對象
console.log(r.includes(2));
r.foreach(console.log);
console.log(r);
// ----------使用構造函數來定義 ”范圍類“------------
function Range(from, to) {
// 儲存 范圍對象 得其實位置 喝結束位置
// 這兩個屬性是不可繼承得, 沒個對象都擁有唯一得屬性
this.from = from;
this.to = to;
};
//所有得 范圍獨享 都繼承自這個對象
// 這個屬性得名字必須是 prototype
Range.prototype = {
// 如果下再范圍內, 則返回true 否則 false
// 這個方法可比較數字范圍,也可以比較字符串和日期范圍
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 + ")";}
}