JS Object this.method() breaks via jQuery
Posted
by Peter Boughton
on Stack Overflow
See other posts from Stack Overflow
or by Peter Boughton
Published on 2009-10-09T16:13:31Z
Indexed on
2010/04/22
14:43 UTC
Read the original article
Hit count: 351
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.)
© Stack Overflow or respective owner