Examine this code
var _class=function()
{
this.Test=100;
this.Callback=function(msg)
{
alert(msg+"\r\n"+this.Test);
}
}
function run(call)
{
call("Hello world");
}
var obj=new _class();
run(obj.Callback);
I got the result :
[Alert]
Hello world
undefined
but when i call
obj.Callback(“Hello world”)
i got expected
[Alert]
Hello world
100
why ?
thank for help
There’s no intrinsic relationship between an object and the functions defined “inside” it. The only thing that determines the value of
this(called the “receiving” object) in a function call is the way in which the function is called.object.func(), andthiswill be bound toobject.thisis determined by the first parameter.thiswon’t refer toanythingyour object — it will refer towindow(or whatever the global context is).The trick is that when you want to use a function as if it were a “method” on an object, such that the relationship remains intact even though the function reference has been yanked away from the object, you can pre-bind
thisin a couple of ways:thisin a closure.The first way would look like this:
The second way would look like this:
JavaScript is quite different from languages like C# or Java in this respect. In those languages, a function is sort-of stuck forever in a relationship with its class (or instances of its class). Not JavaScript; it really doesn’t matter at all, in fact, where a function is defined. Your “_class” function would be equivalent if it were written like this:
edit — @jamietre correctly notes that had your “_class” function contained some
vardeclarations or local functions, then there most certainly would be a difference (though not with respect to the waythisbehaves when “Callback” is invoked).edit again — Thanks @Koolinc