它在第 9 章关于类和模块的第 200-201 页。在我看来,下面的这种方法更简单,但下面的注释输出行由于未知原因不起作用:
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 + ")";
},
Z: "ZZZZZZZZZZZZZZZZZZZ",
}
function Range(from,to) {
this.from = from
this.to = to
}
var r = new Range(1,3)
console.log(Range.prototype.Z)
console.log(r.constructor.prototype.Z) //undefined
console.log(r.Z)
console.log(r.includes(2));
console.log(r.toString());
console.log(r); // Does not use Range.toString
r.foreach(console.log); // TypeError