javascriptclassmethodsjsobject

JavaScript Classes: Accessing method from within an Object's function property


I was wondering if it was possible if anyone knew a solution to the problem I am having. Let's say we have the following JavaScript class:

class foo {

    // Class Method.
    makeNoise() {
        console.log("bar");
    }

    // Class Object
    classObject = {
        makeASound: function() {
            makeNoise();
        }
    }
}

Now, if I were to call:

var foo = new foo();
foo.classObject.makeASound();

I would get an error, saying that makeNoise is not defined. Using 'this.' would not work because in this context it would look for a function inside classObject, and so would throw a 'is not a function' error. Is there anyway at all to able to access makeNoise from within an object's function.


Solution

  • You'll need to use an arrow function in order to avoid creating a new context and then use the keyword this in order to access the makeNoise method of the class correctly

    class Foo {
      makeNoise() {
        console.log("bar");
      }
      classObject = {
        makeASound: () => { // arrow function for lexical scope
          this.makeNoise(); // using `this` to refer to the Foo method
        },
      };
    }
    

    You could also use Function.bind() if preferred