let role = { test: (variable) => { // How do I call toLog(variable) from here? }, toLog: (variable) => { console.log(variable); } };
I'd like to call the toLog() function within the test() function but I'm unaware how to.
You can call the same callback function again until condition is true : someFunction(function repeat(result) { if (result. winner) { someFunction(repeat); } });
The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.
It is important to understand that each of the functions we write can be used and called from other functions we write. This is one of the most important ways that computer scientists take a large problem and break it down into a group of smaller problems.
Methods—setting functions as properties of objects. In JavaScript, you can use functions as values, just like numbers, strings, and objects. That means you can pass them as arguments, return them from other functions, and set them as properties of objects.
Standard JS functions use dynamic binding, this
is dependent on who's calling the method on runtime, so if we call it using role.test()
, it will bind this
to role
.
Arrow functions bind this
to the current context. For example, if the code was writtern in the browser's console, this
is bound to the window
object. This is called static lexical binding, which means binding this
to the closure it was defined in.
If you won't use arrow functions, this
will point to the object itself when called by role
:
const role = { test(variable){ this.toLog(variable); }, toLog(variable) { console.log(variable); } }; role.test(5);
In this case, we don't want to bind this
to the outer context, so we'll skip the static binding in favor of the dynamic one.
However, if we'll use this method as a callback, dynamic binding will change this
according to who's running the method. To prevent that, we'll have to use bind
to create an explicit static binding to role
.
const role = { test(variable) { this.toLog(variable); }, toLog(variable) { console.log(variable); } }; let test = role.test; try { test(20); // will throw an error - this.toLog is not a function - because this points to window } catch (e) { console.log(e); } test = role.test.bind(role); test(25); // will work because it's staticly binded to role
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