Passing a function, including its context in javascript

There is something in javascript that I don't understand, and broke an example of the problem into a significant case:

a = function () { this.b = 5; } a.prototype.c = function () { alert(this.b); } var d = new a(); var e = dc; // how do I save a ref to the method including the context (object)?? dc(); // 5 -> ok e(); // undefined -> wtf?? 

So why in the last example the function is called without its context? And how can I call this context?

Thanks in advance: -)

+3
javascript
source share
3 answers

dc is like an unrelated instance method. You can use Function.prototype.bind to create a new function bound to d (the first argument to .bind is this ):

 var e = dcbind(d); 

Or call e with d as the argument to this :

 e.call(d); 
+5
source share

You need to call the method using the object to get the context correctly. So:

 var e = function() { return dc(); }; 

In new browsers, you can use the bind method to do the same:

 var e = dcbind(d); 

In jQuery, for example, there is a proxy method that you can also use in older browsers:

 var e = $.proxy(dc, d); 
+2
source share

This is about resolving the value of this . This is permitted as follows:

 myObject.something();//this in something is myObject window.something();//this is window button.onClick=function();//this when button is clicked is button 

How to solve this is already set, this is a common error with passing callbacks, as in the following example, using setTimeout

 var test = function () { var me = this;// set reference to this this.sayAgain=function(){ console.log("Hi, I am "+me.toString()); } } test.prototype.toString=function(){ return "test"; } test.prototype.say = function () { console.log("Hi, I am "+this.toString()); } var t = new test(); setTimeout(t.say,50);//=window passing functon without ref to this setTimeout(function(){ t.say(); },150);//=test passing ref with function setTimeout(t.sayAgain,200);//=test using me as the saved this context 

The second timeout passes closure to setTimeout, if you plan to pass the callback hundreds of times, but only create several instances of test objects, then implementing the latter (sayAgain) will work a little better.

This is because you create a closure when creating a test instance, but not when passing sayAgain as a callback, if you create many test instances and do not skip say to remove this.me and this.sayAgain from the function body many times and pass say as a closure.

You can use Function.prototype.bind , but it is not supported in IE <8, and I'm not sure if this will create a closure, as in my example, using t.say .

+1
source share

All Articles