Can't use the String.prototype.match function as a function for Array.some?

This does not work:

var s = '^foo';
console.log(['boot', 'foot'].some(s.match));

Uncaught TypeError: String.prototype.match called on null or undefined

But it does:

var s = '^foo';
console.log(['boot', 'foot'].some(function(i) { return i.match(s) }));

Why is this? I imagine somehow the function is String.prototype.matchtoo "primitive" or something like that, but why exactly? Since I am not using ES2015, the second version looks rather verbose. Is there an alternative?

EDIT

When I wrote above, I really got it back compared to my actual need, which corresponded to one line for several regular expressions. But thanks to the great answers and comments below, I understand [/^foo/, /^boo/].some(''.match, 'boot').

+4
source share
2 answers

Javascript . s.match - , , s. , , , :

"foo".match === "bar".match 
//= true

, Javascript this . - , .

, this, bind, @Felix King. someFunction.bind(someObject) , function(arg1, arg2,...) { return someObject.someFunction(arg1, arg2,...); }, .

+3

: this , ! (: )

s.match .some, this, (, window), , .

.. :

String.prototype.match.call(window, 'foo')

, this .

, this:

['boot', 'foot'].some(s.match.bind(s));

this:

+6

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


All Articles