Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing around function including its context in javascript

Tags:

javascript

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 :-)

like image 490
Silverdust Avatar asked May 04 '26 11:05

Silverdust


2 Answers

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);
like image 197
Blender Avatar answered May 06 '26 01:05

Blender


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);
like image 20
Guffa Avatar answered May 05 '26 23:05

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!