You’re having difficulty understanding the
ES6 introduced the
classkeyword into the language. It did not, however, introduce a new model of object-oriented inheritance. The
classkeyword provides syntactic sugar for expressing prototype properties and constructor functions as described in this article.
There are few language features that in concert make inheritance work.
car.toString()results in using the
toStringmethod from the car object's prototype if
caritself doesn't contain such method. The search continues recursively to the prototype of the prototype until a match is found or the chain is exhausted.
new Car()creates a new object with prototype set to the value of
Car.prototype. This allows setting up prototype chain for new objects. Note that
new Car()only makes sense when
Caris a function. Such function is also known as a constructor function.
- Calling a function property of an object, the value of
thisis bound to the containing object. For example
thisvalue set to
"abc". This allows code reuse - executing the same code lines with different value of
this. A function property of an object is also called a method.
Let's create an example that calculates the perimeter of a rectangle with object-oriented programming.
First a constructor function
Rectangle is defined. The convention is to capitalize function names that are to be called with
new to separate them from other functions. The constructor function is initially given an empty object as the value of
this and the code populates it with
y properties for later use.
Then, a function property is added to
Rectangle.prototype that calculates the perimeter using the object's
y properties. Notice the use of
this that allows the same code to work on multiple objects with different values for the variables.
Finally, a new
Rectangle object called
rect is created. It inherits from
Rectangle.prototype and allows us to call
rect.perimeter() and print the results to the console.
Misleading prototype property name
prototype property of the object. The former is used when looking up non-existent properties in the prototype chain. The latter is used for objects created using
In our example,
Rectangle.prototype will be the the prototype value used for objects created with
new Rectangle() and the prototype of
The value holding the prototype of an object is sometimes called the internal prototype link. It's also been historically called __proto__, a name that has some controversy. To be politically correct, it can be called the value that's returned from
Node doesn't wait for your database call to finish?
Learn how asynchronous calls work and make your app run as you intended. Get short email course on asynchronicity and two chapters from Finish Your Node App.