The new
keyword is a relatively simple but extremely useful part of JavaScript's class system. The first thing that you need to understand about new is that it doesn't create objects in the same way as other languages. In JavaScript, every variable is either a function, object, or primitive, which means that when we refer to a class, what we're really referring to is a specially designed initialization function. Creating this class-like function is as simple as defining a function that modifies this and then using the new keyword to call that function.
Normally, when you call a function, its this is obvious. For instance, when you call the turnPage
method of a book object, the this
method inside turnPage
will be set to this book object, as shown here:
var simpleBook = {currentPage: 3, pages: 60}; simpleBook.turnPage = function() { this.currentPage += 1; return this.currentPage; } simpleBook.turnPage(); // == 4
Calling a function that isn't attached to an object (in other...