Search code examples
javascriptthis

javascript function scope accessing "this"


I have the following sample code. I'm trying to get the this.key inside the namespace function but it's always returning undefined despite me changing the function call, or using arrow approach etc.

class Sample {
  key = '';

  constructor(key) {
    this.key = key;
  }

  myNamespace = {
    saySomething: function(message) {
      console.log('message:', message);
      console.log('key:', this.key);
    }
  }

  getTheKey() {
    console.log('key', this.key);
  }
}


let sample = new Sample('thekey');
sample.myNamespace.saySomething('message'); // shows-> key: undefined
sample.getTheKey(); // shows-> key: thekey

Solution

  • The whole point of your myNamespace property seems more than just questionable, but if you insist and still need a function that is bound to your class instance, just bind the function in the constructor, or use an arrow function which does not have its own this, but keeps this whatever it pointed to at the time of definition: (code example demonstrates both):

    class Sample {
      key = '';
    
      constructor(key) {
        this.key = key;
        this.myNamespace.saySomething = this.myNamespace.saySomething.bind(this);
      }
    
      myNamespace = {
        saySomething: function(message) {
          console.log('message:', message);
          console.log('key:', this.key);
        }
      }
      
      myOtherNamespace = {
        saySomething: (message) => {
          console.log('message:', message);
          console.log('key:', this.key);
        }
      }
    
      getTheKey() {
        console.log('key', this.key);
      }
    }
    
    let sample = new Sample('thekey');
    
    sample.myNamespace.saySomething('message'); // shows-> key: thekey
    sample.myOtherNamespace.saySomething('other message'); // shows-> key: thekey
    sample.getTheKey(); // shows-> key: thekey