On Jul 31, 5:44 am, "#micah" <micah.a.sm...@gmail.com> wrote:
> I've created a javascript object like so:
>
> var myObj={
> // internally used
> OtherFunction: function(){ alert('hi');},
>
> // externally used
> EditInfo: function(){
> this.OtherFunction();
> }
>
> };
>
> if i bind EditInfo to a button, like so:
There is no such thing as "bind" in javascript. You are assigning the
function to a listener.
>
> $('#myButton').click(myObj.EditInfo)
>
> Then (this) is pointing to the button, not to myObj. Why is that?
The value of a function's this keyword is set *when the function is
called*, not when you define the function. The handler that calls
EditInfo sets its this keyword to the button. Note that the handler is
passed a reference directly to the function, it doesn't call it as
myObj.EditInfo().
Perhaps you need:
...click(function(){myObj.EditInfo();})
Now EditInfo is called as a method of myObj and its this keyword will
be set as you expect.
Incidentally, it is a convention that only functions intended to be
called as conststructors start with a capital letter. If that was the
case here, its this keyword would be a reference to the new object and
your issue goes away.
> I'm using FF3.5
Not relevant to this issue, though there are differences in how the
this keyword is set for listeners between IE and other browsers.
--
Rob