Why doesn't any prototype object work as a forEach callback?

Instead of asking a question, I just wanted this to be a problem, but so far I have not been able to find the answer.

For example, we have an array of strings

x = ['a', '   b', '  c  ']

and I want to trim all the elements. I tried the methods applyand callbut did not work properly:

x.forEach(String.prototype.trim.call)
// Uncaught TypeError: undefined is not a function

x.forEach(String.prototype.trim.apply)
// Uncaught TypeError: Function.prototype.apply was called on undefined, which is a undefined and not a function

What's going on here? apply/ callshould take its first argument from each function, and everything seems fine.

0
source share
2 answers

foo.call()will call the function stored in foo.

i.e. the value thisinside callwill be foo.

, forEach, , this (window ).

window , .

bind , .

0

,

x = ['a', '   b', '  c  ']
x.map(function(item) { return item.trim() })
0

Source: https://habr.com/ru/post/1598957/


All Articles