JS Object this.method() breaks via jQuery

javascript, jquery, json, this

Solution

The identity of `this` is a common problem in javascript. It would also break if you tried to create a shortcut to `doSomething`:

var do = Bob.doSomething;
do(); // this is no longer pointing to Bob!

It's good practice to not rely on the identity of `this`. You can do that in a variety of ways, but the easiest is to explicitly reference `Bob` instead of `this` inside of `doSomething`. Another is to use a constructor function (but then you lose the cool object-literal syntax):

var createBob = function() {
    var that = {};

    that.Stuff = '';
    that.init = function() {
        that.Stuff = arguments[0];
    };

   that.doSomething = function() {
       console.log( that.Stuff );
   };

   return that;   
}

var bob = createBob();

Problem

I'm sure there's a simple answer to this, but it's Friday afternoon and I'm tired. :( Not sure how to explain it, so I'll just go ahead and post example code... Here is a simple object: ``` var Bob = { Stuff : '' , init : function() { this.Stuff = arguments[0] } , doSomething : function() { console.log( this.Stuff ); } } ``` And here it is being used: ``` $j = jQuery.noConflict(); $j(document).ready( init ); function init() { Bob.init('hello'); Bob.doSomething(); $j('#MyButton').click( Bob.doSomething ); } ``` Everything works, except for the last line. When jQuery calls the doSomething method it is overriding 'this' and stopping it from working. Trying to use just `Stuff` doesn't work either. So how do I refer to an object's own properties in a way that allows jQuery to call it, and also allows the object to work with the calling jQuery object? i.e. I would like to be able to do things like this: ``` doSomething : function() { console.log( <CurrentObject>.Stuff + $j(<CallerElement>).attr('id') ); } ``` (Where `<CurrentObject>` and `<CallerElement>` are replaced with appropriate names.)

Original source