I'm trying to understand JavaScript scope better, and am not sure why something isn't working.
I've defined an object like this:
var my_obj =
{
foo:function()
{
this.bar()
},
bar:function()
{
console.log('hello world!');
}
}
my_obj.foo();
But I get the error "TypeError: this.bar is not a function" and I don't understand why.
I am also trying to use another piece of code I wrote earlier from within this new block and that isn't working properly either. Here the following happens:
var my_obj =
{
foo:function()
{
feedback('hello world!');
}
}
my_obj.foo();
feedback = function(msg,y)
{
if( !y )
{
setTimeout(function()
{
feedback(msg,1);
} , 1000 );
return;
}
else
{
console.log(msg);
}
}
This used to work fine (if I called feedback() from within the global scope), but now, feedback is called fine from foo, but then the timed out call to feedback fails unless I call window.feedback() from within setTimeout.
Any ideas on either of these issues?
Thanks
Update
Here is my code (which will give both errors): http://jsbin.com/ecotoj/12/edit
Thanks to Asad for showing me the issue that the context of 'this' was changed within $.ajax (and that you can use jQuery's context option within $.ajax to re-define it)