1

I have the module...

var myModule = (function(){

    var obj = new Object();
    obj.name = "";
    obj.sayName = function(){
        obj.name = "jon";
        console.log(obj.name); 
        console.log(this.name);  
    }
    return obj;

})()

myModule.sayName();

This prints the word 'jon' twice as per the console.log statements.

However I don't really understand why 'this' is correct since it would return the reference to the function and be 'undefined' wouldn't it?

Exitos
  • 29,230
  • 38
  • 123
  • 178
  • 2
    `this` is `obj` because `obj` is `myModule` and you call the function like `myModule.sayName()`, notice the dot. – elclanrs Aug 31 '14 at 10:14
  • But I thought because it is a new function that it will get is's own closure? – Exitos Aug 31 '14 at 10:22
  • This has nothing to do with closures or scope but rather with how `this` works in javascript. Basically if called as `a.b.c()` the `this` in `c` refers to the last name before the last dot - `b`. So in your case the last name before the last dot is `myModule`. See this answer for more info: http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628#13441628 – slebetman Sep 05 '14 at 08:20

1 Answers1

3

You are calling myModule.sayName() so this inside sayName is myModule.

The value of myModule is copy of the object reference from obj (since that is what is returned from the anonymous IIFE).

Therefore obj.name and this.name are the same value.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • but I thought the function sayname has it's own closure all to it's self? I would have to assign this to 'self' in a higher function? – Exitos Aug 31 '14 at 10:19
  • 3
    @Exitos: `sayName` is indeed a closure (over `obj` and a few other things), but that has nothing to do with what `this` is within it. `this` is primarily set by how a function is called, as Quentin said. When you call a function via an expression getting the function reference from an object property (`myModule.sayName();`), during the call to the function, `this` will be the object you got the property from (usually; there are *bound* functions that work differently, and ES6's arrow functions will work differently, but your `sayName` is normal). – T.J. Crowder Aug 31 '14 at 10:22