I have a class in JavaScript (MyClass) which exposes two public functions (funA and funB) as shown:
var MyClass = function(){
this.funA = function(){
console.log("function A");
this.funB();
};
this.funB = function(){
console.log("function B");
};
};
var myObj = new MyClass();
Note how funA calls funB using 'this' keyword.
The following works:
myObj.funA();
But this does not:
var anonymousFun = function(fn){
fn();
}
anonymousFun(myObj.funA);
The reason is when funA calls funB using 'this', the 'this' is set to global context (instead of MyClass) and funB does not exist at global level. The error is:
Uncaught TypeError: this.funB is not a function
The simplest solution that I tried to avoid the issue is to use a variable 'that' inside MyClass and initialize it to 'this'. Then, use that.funB instead of this.funB inside funA:
var MyClass = function(){
var that = this;
this.funA = function(){
console.log("function A");
that.funB();
};
this.funB = function(){
console.log("function B");
};
};
Is this a correct approach? Are there any better solutions available?
We use the Bind() method to call a function with the this value, this keyword refers to the same object which is currently selected . In other words, bind() method allows us to easily set which object will be bound by the this keyword when a function or method is invoked.
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
bind is a method on the prototype of all functions in JavaScript. It allows you to create a new function from an existing function, change the new function's this context, and provide any arguments you want the new function to be called with.
You can use call() / apply() to invoke the function immediately. bind() returns a bound function that, when executed later, will have the correct context ("this") for calling the original function. So bind() can be used when the function needs to be called later in certain events when it's useful.
If you're compiling your JS with Babel you can use class property initilizer syntax to create functions that are bound to this
:
class MyClass {
funA = () => {
console.log('function A')
this.funB()
}
funB = () => {
console.log('function B')
}
}
You can use the Function.bind
method to attach an object which is to be used as "this" when the function is called.
anonymousFun(myObj.funA.bind(myObj));
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