[英]JavaScript anonymous function in the for loop error
Hello I was reading "JavaScript: the definitive guide" 6th edition and tried one of the examples at 9.1 Classes and Prototypes. 您好我正在阅读“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 + ")";
}
};
Loading this into console throws an error 将其加载到控制台会引发错误
Uncaught TypeError: Illegal invocation class.js:31.
未捕获的TypeError:非法调用class.js:31。 range.methods.foreach class.js:31 (anonymous function)
range.methods.foreach class.js:31(匿名函数)
I guess intention of foreach method is to pass a function name as an argument 我想foreach方法的意图是将函数名称作为参数传递
var r = range(1, 3);
r.foreach(console.log);
Any ideas how to fix this error? 任何想法如何解决此错误?
It happens because you detached log
method from console
object, while console.log
expects context ( this
) to be console
, not Window
as it becomes when you lose context. 这是因为您从
console
对象中分离了log
方法,而console.log
期望上下文( this
)是console
,而不是Window
,因为当您丢失上下文时它就变成了。 If you want to use console.log
as a function you should explicitly tell it what context to use. 如果要将
console.log
用作函数,则应明确告诉它要使用的上下文。
r.foreach(console.log.bind(console));
Function.prototype.bind is your friend in this case. 在这种情况下, Function.prototype.bind是你的朋友。
For future readers: ES6 style would also allow you to use arrow functions for this which would be even more concise: 对于未来的读者:ES6风格也允许您使用箭头功能,这将更简洁:
r.foreach(x => console.log(x))
Log cannot be called outside of the console object, you're passing in the function, but not the context. 无法在控制台对象外部调用日志,而是传入函数,而不是上下文。
r.foreach(function(a){
console.log(a);
});
This works without any issues. 这没有任何问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.