Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind an inline anonymous function?

Tags:

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     });   } }; 
like image 801
erosman Avatar asked Jun 28 '14 14:06

erosman


People also ask

How do you assign an anonymous function to a variable?

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.

How do you execute an anonymous function?

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.

Can you pass a anonymous function as an argument to another function?

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.

How do you call anonymously in HTML?

var anon = function() { alert('I am anonymous'); } anon();


1 Answers

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); }); 
like image 138
Quentin Avatar answered Sep 19 '22 15:09

Quentin