|You Don't Know JS: this & Object Prototypes|
Author: Kyle Simpson
For example, the way this works is very simple and there are only two general cases. Either it is being used within a function called without the use of the new operator when it is the call context, i.e. the object that called the function; or it is used in a function with the use of the new operator when it is a reference to the new object being constructed.
Once you have these two ideas in your head you can start to explore how they affect the meaning of the code you write. The book starts out by exploring the meaning of the code and makes a list of different conditions that this takes on the two meanings without really ever summing it up in a nutshell. The result is you are likely to understand the use of this better after reading the book but you might just end up confused.
This tendency to over-complicate runs throughout the book. Chapter 1 starts with some things that this isn't but introduces the call method rather than staying simple with an object-based call. It then goes into a side issue of how a function can refer to itself and this is not by using this - at the end of this chapter you stand to be more confused by this.
Chapter 2 attempts to sort it out by explaining that this is the call context. Here we meet the confusion caused by using strict, i.e.with no default to the global object for this if you call a function directly.
The summary of how this gets a value would be better done by explaining that it is the call context if you don't use new and it is the constructed object if you do. Then you can explain that the call method lets you set the call context and strict messes up the use of the global object.
After covering this in detail the book goes off at a slight tangent to consider Objects - getters, setters, properties and so on. Chapter 4 goes over class-based object-oriented programming and uses the example of an inheritance hierarchy vehicle -> car and so on.
The book closes with a look at how to use class and no class "inheritance" and a look at ES6 which is constantly referred to as being beyond the scope of the book, but coming soon in a next book in the series.
|Last Updated ( Wednesday, 14 June 2017 )|