javascriptjsobject

JS Calling functions from a nested object inside this object


actually im trying to run the following code:

var myObj = {
  subObj: {
    methodA: (parA) => {
      this.methodB(parA); //This is not working
    },
    methodB: (parB) => {
      console.log(parB);
    }
  }
}

myObj.subObj.methodA('Hello World');
i get the error "Uncaught TypeError: this.methodB is not a function".

Why am i getting this error? Isn't "methodB" in scope of methodA via 'this'?

Thank you very much


Solution

  • Arrow functions don't have separate this.

    Hence doing

    var myObj = {
      subObj: {
        methodA: (parA) => {
          this.methodB(parA); // `this` will always be window / outer context as arrow functions will not bind `this` at runtime.
        },
        methodB: (parB) => {
          console.log(parB);
        }
      }
    }
    
    
    myObj.subObj.methodA('Hello World'); // fails as `this.methodB` in your `methodA` is equivalent to `window.methodB` which is not present
    

    is similar to doing:

    var myObj = {
      subObj: {
        methodA: function(parA) {
          this.methodB(parA);
        },
        methodB: function(parB) {
          console.log(parB);
        }
      }
    }
    
    myObj.subObj.methodA.call(window || {}, 'Hello World');  // where window || {} is the lexical / outer scope to your function.
    

    In the latter's case, things will work when you do the following:

    myObj.subObj.methodA('Hello World');
    

    Since normal functions use this of the caller and you call methodA as myObj.subObj.methodA, this = myObj.subObj. Hence this.methodB is available as it's equivalent to myObj.subObj.methodB