简体   繁体   中英

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.

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. range.methods.foreach class.js:31 (anonymous function)

I guess intention of foreach method is to pass a function name as an argument

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. If you want to use console.log as a function you should explicitly tell it what context to use.

r.foreach(console.log.bind(console));

Function.prototype.bind is your friend in this case.

For future readers: ES6 style would also allow you to use arrow functions for this which would be even more concise:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM