JS Object this.method() breaks via jQuery
- by Peter Boughton
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.)