Skip to Content
Mastering JavaScript Functional Programming - Second Edition
book

Mastering JavaScript Functional Programming - Second Edition

by Federico Kereki
January 2020
Intermediate to advanced
470 pages
11h 13m
English
Packt Publishing
Content preview from Mastering JavaScript Functional Programming - Second Edition

Handling the this value

A classic problem with JavaScript 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 that problems are avoided. Look at the following code for an example of the possible problems: 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 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 JavaScript and ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering JavaScript Functional Programming

Mastering JavaScript Functional Programming

Federico Kereki

Publisher Resources

ISBN: 9781839213069Supplemental Content