Search code examples
typescript

Access this in a function which is a property of an object


the title may not be clear, so here is an example of what I'm trying to achieve :

const myObj = {
  propA: 'foo',
  propFunc: (arg) => arg + this.propA
}

Basaically, my object has a function as one of its properties, and I want that function to be able to access other properties of the object.

I want to do it like this so I can dynamically change the value or propA and have propFunc access the new value once called.

And so I can define new variables like so, simply overriding propA, and not having to redefine propFunc :

const myObj2 = {...myObj, propA: 'bar' };

Predictably, the compiler is not happy on my use of this.

Is it possible to do it or not? Thanks


Solution

  • Arrow functions do not have their own this context, they inherit the this value from the enclosing scope.

    You can try this:

    const myObj = {
      propA: 'foo',
      propFunc: function(arg) {
        return arg + this.propA;
      }
    }
    
    or the shorthand :
    
    const myObj = {
      propA: 'foo',
      propFunc(arg) {
        return arg + this.propA;
      }
    }
    
    console.log(myObj.propFunc('hello')); // Output: "hellofoo"
    
    const myObj2 = {...myObj, propA: 'bar' };
    
    console.log(myObj2.propFunc('hello')); // Output: "hellobar"