0

I have defined a module using object literal notation as follows:

   var myModule = {
                myProperty: "someValue",
                myConfig: {
                       useCaching: true,
                       language: "en"
                },
                saySomething: function () {
                       console.log( "XXX" );
                },

                functionA: function () {
                       // do something
                ),
                functionB: function () {
                      // need call functionA
                     myModule.functionB();  // style 1
                     this.functionB();      // style 2
                )
    };

What's the purpose using keyword this, what's the difference between style 1 & 2. I also noticed some people use var that = this, and then that.func() , how is this better? And where should I put the var that = this, in my module.

What's the best practice for object literal notation?

9blue
  • 4,693
  • 9
  • 29
  • 43

1 Answers1

0

First of all, the value of this depends on what you call the method on. When you do myModule.func(), this inside func will be myModule. When you do more complicated things like:

function delegator(func) {
  func();
}

delegator(myModule.functionB);

..., you will notice that this inside func will no longer refer to myModule, but will instead be the global object (or undefined if you're using strict mode).

That is the reason people alias that to this. In your scenario, there is no place where you can put that alias, because you're defining an object.

It's safe to use this when you know the method will always be called on your module, otherwise you should use the myModule.functionB() approach.

Tibos
  • 27,507
  • 4
  • 50
  • 64