1

Is it possible to do the same as in Java and pass a function reference to a function of a particular object in javascript?

Consider the following code:

_.every(aS, function (value) {
    return exp.test(value);
});

I would like to do:

_.every(aS, exp.test);

I.e. cause the test function of that particular RegExp to be called.

Is this possible in javascript?


Answer: Yes it is possible, take a look at chapter 2 of You Don't Know JS: this & Object Prototypes section Hard Binding.
Roland
  • 7,525
  • 13
  • 61
  • 124

2 Answers2

3

Yes, but to be sure the this reference is working correctly inside the exp.text implementation, you should bind it:

_.every(aS, exp.test.bind(exp));

For some functions, this may not be necessary (when they don't use the this reference), but it does not hurt.

For more information on this, see How does the this keyword work.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • A good explanation is at [chapter 2 of You Don't Know JS: this & Object Prototypes](https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md) section *Hard Binding*. – Roland Jun 15 '17 at 06:06
1

Yes, but you have to have a bit of an understanding of how this works in JS.

Basically, you have to bind the function to the object like this.

_.every(aS, exp.test.bind(exp))

Basically, when you use bind, it makes sure that no matter where the function is called, the this is always bound to the object you pass into the function. If you didn't call bind then this would be bound to whatever the environments global object is, window in the browser.

Adam LeBlanc
  • 932
  • 7
  • 21