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






No comments:

Post a Comment