this binding JavaScript is lost and solutions

Common mistake: confused this binding rules.

code show as below:

var obj = {
  id: 'vexekefo',
  cool() {
    console.log(this.id);
  }
};
var id = 'someone';
obj.cool();  // vexekefo

setTimeout(obj.cool, 100); // someone

Why is this the output?
setTimeoutBuilt-in functions make this binding is lost, no longer the object obj id value. Thus id value instead of the output of global scope obj.id.

Two kinds of solutions: arrow function and bind()
principle function of the arrow is: covered with the original value of this current lexical scope.
bind is: the first parameter of this function is specified bind.

// 箭头函数
var obj = {
  id: 'vexekefo',
  cool() {
    console.log(this.id);
  }
};
var id = 'someone';

obj.cool();
setTimeout(() => {obj.cool()}, 100);

// bind()
var obj = {
  id: 'vexekefo',
  cool: function(){
    console.log(this.id);
  }
};
var id = 'someone';

obj.cool();
setTimeout(obj.cool.bind(obj), 100);

Guess you like

Origin www.cnblogs.com/wljqds/p/11318802.html