您好我正在阅读"JavaScript:权威指南"第6版,并在9.1 Classes和Prototypes中尝试了其中一个示例.
function range (from, to) {
var r = Object.create(range.methods);
r.from = from;
r.to = to;
return r;
}
range.methods = {
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 + ")";
}
};
Run Code Online (Sandbox Code Playgroud)
将其加载到控制台会引发错误
未捕获的TypeError:非法调用class.js:31.range.methods.foreach class.js:31(匿名函数)
我想foreach方法的意图是将函数名称作为参数传递
var r = range(1, 3);
r.foreach(console.log);
Run Code Online (Sandbox Code Playgroud)
任何想法如何解决此错误?