Zack Gao
Zack Gao

Reputation: 568

Why is call necessary in this Javascript example?

Here's the problem (called "Compose functions (T Combinator)" on codewars.com, in case you want to try it out in the original environment):

Let's make a function called compose that accepts a value as a parameter, as well as any number of functions as additional parameters.

The function will return the value that results from the first parameter being used as a parameter for all of the accepted function parameters in turn. If only a single parameter is passed in, return that parameter.

So:

var doubleTheValue = function(val) { return val * 2; }
var addOneToTheValue = function(val) { return val + 1; }

compose(5, doubleTheValue) // should === 10
compose(5, doubleTheValue, addOneToTheValue) // should === 11

Here was one of the possible solutions:

var compose = function(initialValue) {
  var functions = Array.prototype.slice.call(arguments, 1);
  return functions.reduce(function(previousResult, func){
    return func.call(this, previousResult);
  }, initialValue); 
}

Why do we need to return func.call(this, previousResult) rather than just func(previousResult)? The latter only works in some cases. What will "this" default to without the call?

Upvotes: 3

Views: 247

Answers (3)

Nicholas Hazel
Nicholas Hazel

Reputation: 3750

Why do we need to return func.call(this, previousResult) rather than just func(previousResult)?

this defaults to our window.

Basically, we're giving it a secondary value in order to further our progression down the line.

If you were to call simply previousResult, the JS doesn't know where to look to find such a thing. Your are referencing the window if you don't call a prior parameter. This is very common in most OOP languages. You can't look for your value IN window without further defining that you want something IN window.

Essentially, we are just providing a bogus variable in order to get to the next step in the chain. You will see this a lot with Python and Ruby code.

The reason you set this is because this will equal the parent window, then you know you can find the next variable within that particular parameter.

Simple Example: It's sort of like trying to call a variable in a different function. Just doesn't work without defining your scope first.

Upvotes: 0

Bergi
Bergi

Reputation: 664423

Why do we need to return func.call(this, previousResult) rather than just func(previousResult)?

We don't really. this is not the this value of the compose function (what the author probably intended), but of the reduce callback - where it is specified to be undefined.

What will "this" default to without the call?

undefined as well, see Why is "this" in an anonymous function undefined when using strict?.

Upvotes: 2

Paul
Paul

Reputation: 141839

In strict mode, this will be undefined since there is no calling context.

In non-strict Javascript it will be the global object (window in a browser).

Upvotes: 0

Related Questions