Showing posts with label Advanced-FunctionBinding. Show all posts
Showing posts with label Advanced-FunctionBinding. Show all posts

Friday, May 11, 2018

Solution for losing this - Function binding

Top avoid losing of this , we can wrapping a function.

Example :

Solution I:
1
 2
 3
 4
 5
 6
 7
 8
 9
10
let user = {
  firstName: "TestName",
  sayHi() {
    alert(`Hello, ${this.firstName}!`);
  }
};

setTimeout(function() {
  user.sayHi(); // Hello, TestName
}, 3000);

Now above code will work, since we have passed user.sayHi() as function (Outer lexical environment). So it will work like normal method call.

However, using arrow function (ES6) will short your code and solve this problem very easily without any confusing.

Example II: Arrow function :

Solution II:

1
2
3
4
5
6
7
8
let user = {
  firstName: "TestName",
  sayHi() {
    alert(`Hello, ${this.firstName}!`);
  }
};

setTimeout(() => user.sayHi(), 3000);


Example III:

Solution III:
Using bind built in method

Before proceeding we must know its syntax.

let boundFunc = func.bind(context);


Below is the example code and its explanation is below. Now you can understand better.


1
 2
 3
 4
 5
 6
 7
 8
 9
10
let user = {
  firstName: "TestName"
};

function func() {
  alert(this.firstName);
}

let funcUser = func.bind(user);
funcUser(); // TestName

From the above example, func method bind was done and assigned to funcUser. So calling the funcUser will provide the correct result. Means, this bind with user object.

Example IV:

Binding with Object method:



1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let user = {
  firstName: "TestName",
  sayHi() {
    alert(`Hello, ${this.firstName}`);
  }
};

let sayHi = user.sayHi.bind(user); // (*)

sayHi(); // Hello, TestName

setTimeout(sayHi, 1000); // Hello, TestName






Losing this - Function binding


Actually, this is an old concept only because If you are using ES6 and you don not worry about this. To know more about function binding , check below.

Example Scenario :

Just assume that, you are using setTimeout with object methods or you are trying to passing object methods, then you will loss "this" power.

Means, using this.xxxxx something will give you the result as undefined.

Example code for losing "this":


1
2
3
4
5
6
7
8
let user = {
  firstName: "TestName",
  sayHi() {
    alert(`Hello, ${this.firstName}!`);
  }
};

setTimeout(user.sayHi, 3000); // Hello, undefined!

Explanation:

1. We have set 3 seconds for setTimeout function at line no 8.

2. Now sayHi method will be executed and it try to print firstName with the help of this.firstName.

3. As "this" was lost , it will print undefined.