Module pattern and this

Module pattern and this
0

#1

Hi,
I try to get the keyword this in this module:
and this is undefined?
I learned all the function in js are object and a key word this is a part of the design in OO world ?

//https://toddmotto.com/mastering-the-module-pattern/#revealing-module-pattern
let TicTacToe = (function () {

  let data = { name : 'Xavier'}, self = this
  
  let _privateMethod  = function () {
    // private
    console.log(this)
  };

  let someMethod = function () {
    // public
    _privateMethod()
    console.log(data.name);
  };

  let anotherMethod  = function () {
    // public
  };
  
  //return an object
  return {
    someMethod: someMethod,
    anotherMethod : anotherMethod 
  };

})();
TicTacToe.someMethod()
TicTacToe.anotherMethod ()

#2

Functions in JS are objects, but that does not mean this inside a function refers to it. It usually does not.

In case of your example, it goes like that:

  1. You are calling TicTacToe.someMethod() - someMethod is function like any other, but it is called as a method, so this will refer to the object it is called on (the TicTacToe object)
  2. However, someMethod does not use this by itself in any way. It just calls _privateMethod, but not as a method, just as a normal function (“being called as a method” does not propagate to other functions you call inside your method). Which means this inside _privateMethod will either be undefined (in strict mode) or confusing (in non-strict mode).

A possible solution is to tell the _privateMethod call what is it supposed to use as this. Assuming you want to use the same thing someMethod has for this when called as a method, you do it like that:

let someMethod = function () {
  // public
  _privateMethod.call(this);
  console.log(data.name);
 };

I’m fresh off reading You Don’t Know JS - this & Object Prototypes, I absolutely recommend it :slight_smile:


#3

You can also _privateMethod = _privateMethod.bind(this) if you will are sure you always want the method to refer to the same this