0

Wondering what the difference between the two code below. In the first case I used this to refer to the object and in the second case I used the object name. Although both works I was wondering whether there is any real difference between the two.

(function() {
var app = {
    init: function () {
        app.addLun('Hello');
    },
    addLun: function(a) {
        console.log(a);
    }
};
});
})();

and

var app = {
    init: function () {
        this.addLun('Hello');
    },
    addLun: function(a) {
        console.log(a);
    }
};
});
})();
tawheed
  • 4,885
  • 8
  • 33
  • 61

3 Answers3

1

this refers to the context/scope of the function, so depending on how you call it, it could refer to app, window, or many other scopes...

app refers to the actual app object if it exists in that scope.

Naftali aka Neal
  • 138,754
  • 36
  • 231
  • 295
0

Using this and app are absolutely not the same. Take this (slightly contrived) example:

var app = {
    init: { 
        foo: function () {
            // Think 'this' is app? 
            this.addLun('Hello');
        }
    },
    addLun: function(a) {
        console.log(a);
    }
};

var app2 = {
    init: { 
        foo: function () {
            app2.addLun('Hello');
        }
    },
    addLun: function(a) {
        console.log(a);
    }
};

app2.init.foo(); // prints Hello
app.init.foo();  // error - no method called addLun

this is the current context, app is the object you have just created.

RobH
  • 3,676
  • 1
  • 21
  • 41
-1

Yes, there is difference. If you want to have more, that one instance of app object (for example, you can clone it with jQuery.extend()), you need to use second variant for correct work.

Maxim Pechenin
  • 324
  • 1
  • 13