Module pattern and this

Module pattern and this


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 ?

let TicTacToe = (function () {

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

  let someMethod = function () {
    // public

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

TicTacToe.anotherMethod ()


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;

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


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