There is something I don't understand in javascript and broke down a sample problem to an essential case:
a = function () {
this.b = 5;
}
a.prototype.c = function () {
alert(this.b);
}
var d = new a();
var e = d.c; // how do I save a ref to the method including the context (object)??
d.c(); // 5 -> ok
e(); // undefined -> wtf??
So why is the function being called without its context in the last example? And how can I call it with the context?
Thanks in advance :-)
d.c is like an unbound instance method. You can use Function.prototype.bind to create a new function that's bound to d (the first argument to .bind is the this argument):
var e = d.c.bind(d);
Or call e with d as the this argument:
e.call(d);
You need to call the method using the object to get the context right. So:
var e = function() { return d.c(); };
In newer browsers you can use the bind method to do the same:
var e = d.c.bind(d);
In jQuery for example there is the proxy method that you can use also in older browsers:
var e = $.proxy(d.c, d);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With