How to Use an Object Method as a Callback Function

how to use callback functions with object/method pair

You could simply pass the method object to the class:

called = CallMe(obj.Func)

To expand a bit, instance methods are really just the original class function:

>>> obj.Func.__func__
<function __main__.WithClassMethod.Func>

which, during access on an instance (obj.Func) are transformed via a descriptor (__get__) that attaches self (the instance) to them:

>>> obj.Func.__self__
<__main__.WithClassMethod at 0x7fbe740ce588>

so you can pretty much do anything you want with methods as with functions.

Invoke a javascript object method from within a callback

Save the correct this, when it is in scope, into a variable. Then you can reference it later:

 this.startRequest = function() {
var myself = this;
GM_xmlhttpRequest({
'method': 'GET',
'url': "http://www.google.com/",
'onload': function (xhr) {
myself.myCallback();
}
});
};

How to use object methods as callbacks to modify object properties in javascript

This is a well-known "quirk" of Javascript: when you call your myCallback function from the request function (or from setTimeout), the context of the call is the request function - this means that this refers to request, not to your Database object. So, for example, if you call myCallback from a DOM event handler, then this will refer to the DOM element.

There are a number of good answers explaining this: here or here.

Now, for a solution to your specific problem, here's a code sample. I took the liberty of rewriting your second example using ES6 classes, since I think it's a little clearer that way:

class Database {  constructor() {    console.log('<Executing constructor>');    this.value = 'initial constructor data';
// bind `this` to the `myCallback` function so that whenever we call // `myCallback`, it will always have the correct `this` // this.myCallback = this.myCallback.bind(this); }
myCallback() { console.log('<Executing callback>'); this.value = 'callback modified data'; }}

let d = new Database(); //global target for async modification
main();function main(){ console.log("First, the object contains: ",d.value); setTimeout(d.myCallback, 1 * 1000);//seconds wait time console.log("Back in main, the object contains: ", d.value); setTimeout(function() { console.log("After waiting patiently, the object contains: ",d.value); }, 2 * 1000);//seconds wait time};

Where is my 'this'? Using objects method as a callback function

"this" is late binding. that is, it gets bound to a thing just before the function is executed. What it is bound to depends on how you call your function.

if you call it like (function invokation):

   myfunction();

"this" is bound to the global object

if you call it like (method invokation):

   myobject.myfunction();

"this" gets bound to "myobject"

you can also call it like so (call invokation):

   myfunction.call(myobject);

in which case "this" gets bound to myobject

there is also (constructor invokation):

 new MyFunction();

in which "this" gets bound to a newly constructed blank object whose prototype is MyFunction.prototype.

this is how the creators of javascript talk about it, anyway. (and I think it is discussed this way in the spec) Different ways of invoking a function.

the new version of the ecmascript standard (ecmascript5) includes the prototype library's "bind" method, which returns a new function with "this" prebound to something you specify. for instance:

  mynewfunction = myfunction.bind(myobject);
mynewfunction();

the invokation of mynewfunction has "this" already bound to myobject.

How to use an object method (with $this) as a callback in array_filter?

Use an anonymous function that calls isValid()

return array_filter($input, function($x) { return $x->isValid(); });

Object-method callback loses its binding in an event handler when passed as a parameter, but not when hard-coded

You're binding the return value of cb - try binding the function first then calling it:

cb.bind(this)(); 

When I use a method as a callback, it seems to lose access to `this`. Why?

Call .bind:

get_stuff(res.send.bind(res));

and have a look at the MDN documentation about this to get an idea how it works. The value of this is determined by how the function is called. Calling it "normally" (what probably happens with the callback), like

func();

will set this to the global object. Only if a function is called as an object method (or if this is explicitly set with .bind, .apply or .call are used), this refers to the object:

obj.fun(); // `this` refers to `obj` inside the function

.bind allows you to specify the this value without calling the function. It simply returns a new function, similar to

function bind(func, this_obj) {
return function() {
func.apply(this_obj, arguments);
};
}


Related Topics



Leave a reply



Submit