方法一————————————————————————————————————————————————————————————
function Range(from, to) {
this.from = from;
this.to = to;
}
Range.prototype = {
includes: function (x) {
return this.from <= x && this.to >= x;
},
foreach: function (f) {
for (var b = Math.ceil(this.from); b <= this.to; b++) f(b);
},
toString: function () { return "(" + this.from + "----" + this.to + ")"; }
};
方法二:————————————————————————————————————————————————————————————
//Range.js
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 && this.to >= x;
},
foreach: function (f) {
for (var b = Math.ceil(this.from); b <= this.to; b++) f(b);
},
toString: function () { return "(" + this.from + "----" + this.to + ")"; }
};
//通过原型继承创建一个新对象
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 f;
}
测试—————————————————————————————————————————————————————————————————————
var r = new Range(1, 3);
r.includes(2);
r.foreach(function (x) { alert(x); });
alert(r);