I just experienced a behavior in JS which I couldn’t understand: I wanted to create a method which calls String.prototype.replace with some args given, therefore I came up with that:
String.prototype.replace.bind("foo", /bar/g, function(){}).call
I guessed that I would get a function where I would just have to throw a string into to get my replace. Instead, I always get the initial this-value (in this case foo) returned.
Now my questions are:
- Why is JS behaving like that? What does bind really return and how can I get the
this-parameter of.call()? - Is there another way of doing what I want to do without creating a wrapper function?
Why it’s happening
You pass some
thisvalue fromcallto the function returned bybind.bind, however, ignores that value and calls the original function with the boundthis(e.g.foo). In fact,bindis meant to bind thethisvalue. Theargumentsyou can bind is rather something additional.Solving it
Without a wrapper function I don’t think you can do what you want. However, with a wrapper function you could do what you’re after:
E.g.