0

I do not understand why the feature does not work , I passed into the method foreach.

 var methods = {
            foreach: function(f){
                for(var i = 0; i <= this.x; i++){
                    f(i);
                }
            }
        };
        function test(x) {
           var t = Object.create(methods);
           t.x = x;
           return t;
        };
        var t = test(10);
        console.log(t.x); //10
        t.foreach(console.log()); //Uncaught TypeError: undefined is not a function

Thx!

3
  • t.foreach(console.log); //Uncaught TypeError: Illegal invocation Commented Feb 5, 2015 at 11:53
  • t.foreach(function(x){console.log(x)}); //1 2 3 ... Thx! Commented Feb 5, 2015 at 11:57
  • Thank you all ! This wrong example I saw in a book by David Flanagan: Javascript Pocket reference 3rd (page number 136) I did not think that there may be errors. Commented Feb 5, 2015 at 12:04

1 Answer 1

1

You are passing the return value of calling console.log(), which isn't a function.

You need to pass an actual function.

Since log only works in the context of console you can't just pass console.log but you could, for instance:

 t.foreach(function (logthis) { console.log(logthis); });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.