'this' is magic, and can be changed by the calling program. jQuery changes it to the target element in event handlers. If you want to use the original object, you have to save a reference to it somewhere. In your example, you are already saving that reference as 'myObject', so the following would work:
var myObject = { o : 'hello', init : function() { alert(myObject.o); //'myObject' doesn't change } } More commonly this is a problem if you're creating multiple instances of an object; then you have to create a variable inside it that remembers what 'this' is supposed to be: var myClass = function() { me = this; me.o = 'hello'; me.init = function() { alert(me.o); //'me' doesn't change } } myObject = new myClass(); The function assigned to init plus the reference to a variable defined outside of it ('me') is called a closure. You'll see people use 'self = this' or '$this = $(this)' for this purpose frequently. Danny On Dec 3, 5:10 pm, sawmac <[EMAIL PROTECTED]> wrote: > I'm trying to wrap my head around objects and object literals. I can't > seem to figure out how to access the object within one of its methods, > when the method is triggered by an event. In other words the context > for 'this' shifts when the method is invoked by a handler. See simple > example below: > > $(document).ready(function () { > > var myObject = { > o : 'hello', > init : function() { > alert(this.o); //'this' changes > } > > } > > myObject.init(); // 'hello' > $(document).click(myObject.init); //'undefined' > > }); > > When the click event calls the init() method, this in alert(this.o) > changes to the document. Is there a way to make 'this.o' always refer > to the object? > > thanks for any help > > --dave