How does .apply(Math, arrayName) work? (javascript)

后端 未结 4 2013
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-16 01:33

There is more than one stackoverflow question about how to find the min or max of an array of values in javascript. This is not that question.

I want to know why pas

4条回答
  •  情深已故
    2021-01-16 01:37

    This (so to speak) is a tricky part of JavaScript.

    When you have a function, there's a magical variable called this. Depending on how you call a function, its context is set differently.

    function myFunction() {
      return this;
    }
    
    var myObject = {
      fn: function() {
        return this;
      }
    };
    
    myFunction();  // the global object. `window` in browsers, `global` in Node.js
    myFunction.apply(Math);  // Math
    myFunction.apply({ hello: "world" });  // { hello: "world" }
    
    myObject.fn();               // myObject
    myObject.fn.apply(myObject); // myObject
    myObject.fn.apply(Math);     // Math
    

    The reason that your examples above work is because min doesn't use this at all, so you can assign it to whatever you want.

提交回复
热议问题