这是js权威指南上的一个例子,我运行的时候报了 Illegal invocation 错误。。我是我不知道为什这样写会报错,求告知。谢谢。代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
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); // Create a range object
r.includes(2); // => true: 2 is in the range
r.foreach(console.log); // Prints 1 2 3
console.log(r); // Prints (1...3)
</script>
</body>
</html>
原因在于
console.log
这个函数实现需要console
作为函数的this