Passing around function including its context in javascript

javascript

Solution

`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);

Problem

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

Original source