Using 'null' vs 'this' in apply or apply () and call () actions in javascript

What is the difference between using thisand nullas a context thisArgfor apply()and methods call()?

function getMax(arr) {
  return Math.max.apply(null, arr);
}

function getMax(arr) {
  return Math.max.apply(this, arr);
}
+4
source share
2 answers

maxis a static function, so it doesn't matter what you pass as this, because it's thisnot used. So your functions are equivalent.

+1
source

The usage value thisis to set the current context when calling the method. For instance:

function Human() {
    this.getMax = function getMax(arr) {
      console.log(this.constructor);
      return Math.max.apply(this, arr);
    }
}

var human = new Human();

human.getMax([1,2]);

this.constructor Human. , .

, null, . , Math.max a, b, c, , .apple.

0

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


All Articles