I am trying to bind
(ie bind(this)
) the inline anonymous callback function to the object
How can it be done?
Simplified example:
var object = { property: function() { this.id = 'abc'; // 'this' binds to the object aFunctionWithCallback(this.id, function(data) { console.log(this); // null }); } };
We write the anonymous function in Javascript by writing function() followed by the parentheses, where we may pass the parameters, and skipping the function name. Then in a pair of curly braces {}, we write our desired code. Finally, we assign this function to a variable.
To turn a normal anonymous function into a self-executing function, you simply wrap the anonymous function in parentheses and add a set of parentheses and a semicolon after it. The benefit of using self-executing anonymous functions is that the variables you create inside of them are destroyed when the function exits.
Summary. Anonymous functions are functions without names. Anonymous functions can be used as an argument to other functions or as an immediately invoked function execution.
var anon = function() { alert('I am anonymous'); } anon();
The same way you always use bind
.
Get a reference to the function (such as is returned by a function expression), and call the bind
method on it.
aFunctionWithCallback(this.id, function(data) { console.log(this); }.bind(this));
JS had added a new feature since this answer was written: arrow functions.
They bind this
lexically instead of determining its value based on how the function is called so you can simply drop one into this code:
aFunctionWithCallback(this.id, (data) => { console.log(this); });
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