0

I started to learn the apply function from this doc

In the following example, the function invocation with apply and that without apply have the same output.

console.log(Math.max(5, 6, 2, 3, 7)); // output:7
console.log(Math.max.apply(null, [5, 6, 2, 3, 7])); // output:7

However, when I adopted the same way on the following example, the outputs are different.

class Animal { 
  speak() {
    return this;
  }
}

let obj = new Animal();
let speak = obj.speak;
console.log(speak()); // output:undefined
console.log(speak.apply(null, [])); // output:null

It seems passing null as the 1st argument of apply may change the behavior of the function. Using undefined does not have this side effect. For example:

console.log(Math.max.apply(undefined, [5, 6, 2, 3, 7])); // output:7
console.log(speak.apply(undefined, [])); // output:undefined

So is it safer to use undefined than null in most cases? (suppose we only focus on cases where there is no this object for the function call)

Richard Hu
  • 287
  • 1
  • 10
  • 2
    The question doesn't make much sense. The first argument sets the value of `this` so if you return the value of `this` from the function then of course it'll return whatever the first argument was. There is no "side effect." – Guy Incognito Dec 11 '20 at 11:15
  • 1
    Does this answer your question? [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – FZs Dec 11 '20 at 11:27
  • 1
    "*suppose we only focus on cases where there is no `this` object for the function call*" - in those cases where the function is expected not to use the `this` argument, it doesn't matter whether you pass `undefined` or `null`. Neither is "safer". The latter is just more convenient to type. – Bergi Dec 11 '20 at 11:29
  • try `console.log(obj.speak());` and see what the method "is supposed to" return. And the next method you should check out: [bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). As in `let speak = obj.speak.bind(obj);` vs `let speak = obj.speak.bind({ foo: 42 });` – Thomas Dec 11 '20 at 11:34

0 Answers0