Why Doesn't Any Object Prototype Work As A Foreach Callback?
Rather than a question, I just wanted it to be a challenge but couldn't find an answer yet. For example, we have an array of strings x = ['a', ' b', ' c '] and I want to trim
Solution 1:
foo.call()
will call the function stored in foo
.
i.e. the value of this
inside call
will be foo
.
The function you pass to forEach
gets called without explicit context, so the value of this
will be the default object (window
in a browser).
window
is not a function, so it errors.
You can use bind
to create a new function that calls a function with a specific context.
Solution 2:
Try this,
x = ['a', ' b', ' c ']
x.map(function(item) { return item.trim() })
Post a Comment for "Why Doesn't Any Object Prototype Work As A Foreach Callback?"