Search code examples
javascriptthis

What will be the value of 'this' for a function in an array in an object?


What will be the value of this for the function in the methodArray array, which is a property of myObject? Also, is methodArray[0] a normal function or a method?

let myObject = {
  property: "Prakhar",
  methodArray: [
    function () {
      console.log(this);
    },
  ],
};

myObject.methodArray[0]();

On executing this code in browser, it is printing the array. Not sure why it is? Ideally it should be the window object (global) if the function is not a method or myObject if the function is a method.


Solution

  • What will be the value of this inside methodArray function?

    It depends on how the function is invoked.

    For an in-depth overview of this, see MDN > this > Function context. Here's a quoted snippet that applies to the code in your example:

    For a typical function, the value of this is the object that the function is accessed on. In other words, if the function call is in the form obj.f(), then this refers to obj.

    In your example…

    myObject.methodArray[0]();
    

    …the function is invoked as a method at the property 0 of the array methodArray (keep in mind that arrays are objects and property 0 is being accessed using bracket notation), so the value of this will be the array.

    To illustrate further, here is a slightly modified version of your example code which returns the inner this value of the function so that it can be used for comparison outside the function:

    let myObject = {
      property: "Prakhar",
      methodArray: [
        function () {
          return this;
        },
      ],
    };
    
    const thisResult = myObject.methodArray[0]();
    
    console.log(thisResult === myObject.methodArray); // true


    Also is methodArray[0] a function or method?

    A method is a function which is a property of an object. So the function at property 0 of the array object is a method.