官术网_书友最值得收藏!

Handling the this value

A classic problem with JS is the handling of this -- whose value isn't always what you expect it to be. ES2015 solved this with arrow functions, which inherit the proper this value, so problems are avoided. To see an example of the possible problems, in the following code, by the time the timeout function is called, this will point to the global (window) variable instead of the new object, so you'll get an undefined in the console:

function ShowItself1(identity) {
this.identity = identity;
setTimeout(function() {
console.log(this.identity);
}, 1000);
}

var x = new ShowItself1("Functional");
// after one second, undefined is displayed

There are two classic ways of solving this with old-fashioned JS5, plus the arrow way of working:

  • One solution uses a closure, and defines a local variable (usually  named that or sometimes self), which will get the original value of this so it won't be undefined
  • The second way uses .bind(), so the timeout function will be bound to the correct value of this
  • And the third, more modern way, just uses an arrow function, so this gets the correct value (pointing to the object) without further ado

We will also be using .bind().  See the Of lambdas and etas section.

Let's see the three solutions in actual code:

function ShowItself2(identity) {
this.identity = identity;
let that = this;
setTimeout(function() {
console.log(that.identity);
}, 1000);

setTimeout(
function() {
console.log(this.identity);
}.bind(this),
2000
);

setTimeout(() => {
console.log(this.identity);
}, 3000);
}

var x = new ShowItself2("JavaScript");
// after one second, "JavaScript"
// after another second, the same
// after yet another second, once again
主站蜘蛛池模板: 原平市| 唐河县| 禹城市| 南宁市| 百色市| 潼南县| 上思县| 根河市| 凤凰县| 章丘市| 宜城市| 沁阳市| 瓦房店市| 襄汾县| 自治县| 晋宁县| 家居| 岳阳市| 综艺| 德兴市| 盈江县| 东宁县| 高阳县| 刚察县| 莱阳市| 色达县| 区。| 临城县| 德惠市| 沁水县| 扬州市| 鄂州市| 新沂市| 宝坻区| 徐闻县| 迁西县| 南部县| 黔西| 长垣县| 和田县| 岱山县|