This article is part of a web dev tech series from Microsoft. Thank you for supporting the partners who make SitePoint possible.
A lot of my friends are C# or C developers. They are used to using inheritance in their projects and when they want to learn or discover JavaScript, one of the first question they ask is: “But how can I do inheritance with JavaScript?”
Actually, JavaScript uses a different approach than C# or C to create an object-oriented language. It is a prototype-based language. The concept of prototyping implies that behavior can be reused by cloning existing objects that serve as prototypes. Every object in JavaScript decends from a prototype which defines a set of functions and members that the object can use. There is no class. Just objects. Every object can then be used as a prototype for another object.
This concept is extremely flexible and we can use it to simulate some concepts from OOP like inheritance.
Let’s visualize what we want to create with this hierarchy using JavaScript:
First of all, we can create ClassA easily. Because there are no explicit classes, we can define a set of behavior (A class so…) by just creating a function like this:
<span>var <span>ClassA</span> = function() { </span> <span>this.name = "class A"; </span><span>}</span>
This “class” can be instantiated using the new keyword:
<span>var a = new ClassA(); </span><span>ClassA.prototype.print = function() { </span> <span>console.log(this.name); </span><span>}</span>
And to use it using our object:
a<span>.print();</span>
Fairly simple, right?
The complete sample is just 8 lines long:
var ClassA = function() { this.name = "class A"; } ClassA.prototype.print = function() { console.log(this.name); } var a = new ClassA(); a<span>.print();</span>
Now let’s add a tool to create “inheritance” between classes. This tool will just have to do one single thing: clone the prototype:
<span>var inheritsFrom = function (child<span>, parent</span>) { </span> child<span>.prototype = Object.create(parent.prototype); </span><span>};</span>
This is exactly where the magic happens! By cloning the prototype, we transfer all members and functions to the new class.
So if we want to add a second class that will be a child of the first one, we just have to use this code:
<span>var <span>ClassA</span> = function() { </span> <span>this.name = "class A"; </span><span>}</span>
Then because ClassB inherited the print function from ClassA, the following code is working:
<span>var a = new ClassA(); </span><span>ClassA.prototype.print = function() { </span> <span>console.log(this.name); </span><span>}</span>
And produces the following output:
a<span>.print();</span>
We can even override the print function for ClassB:
var ClassA = function() { this.name = "class A"; } ClassA.prototype.print = function() { console.log(this.name); } var a = new ClassA(); a<span>.print();</span>
In this case, the produced output will look like this:
<span>var inheritsFrom = function (child<span>, parent</span>) { </span> child<span>.prototype = Object.create(parent.prototype); </span><span>};</span>
The trick here is to the call ClassA.prototype to get the base print function. Then thanks to call function we can call the base function on the current object (this).
Creating ClassC is now obvious:
<span>var <span>ClassB</span> = function() { </span> <span>this.name = "class B"; </span> <span>this.surname = "I'm the child"; </span><span>} </span> <span>inheritsFrom(ClassB, ClassA);</span>
And the output is:
<span>var b = new ClassB(); </span>b<span>.print();</span>
It might surprise you a bit, but Microsoft has a bunch of free learning on many open source JavaScript topics and we’re on a mission to create a lot more with Project Spartan coming. Check out my own:
Or our team’s learning series:
And some free tools: Visual Studio Community, Azure Trial, and cross-browser testing tools for Mac, Linux, or Windows.
To conclude, I just want to clearly state that JavaScript is not C# or C . It has its own philosophy. If you are a C or C# developer and you really want to embrace the full power of JavaScript, the best tip I can give you is: Do not try to replicate your language into JavaScript. There is no best or worst language. Just different philosophies!
This article is part of the web dev tech series from Microsoft. We’re excited to share Project Spartan and its new rendering engine with you. Get free virtual machines or test remotely on your Mac, iOS, Android, or Windows device at modern.IE.
In JavaScript, there are two types of inheritance: classical and prototypal. Classical inheritance, also known as constructor inheritance, is where a new object is created from a class or constructor function. This is similar to how inheritance works in languages like Java or C . Prototypal inheritance, on the other hand, is unique to JavaScript. It involves creating a new object that inherits properties from an existing object. This is done using the Object.create() method or by setting the prototype of the new object to the existing object. The main difference between the two is that classical inheritance uses classes and constructor functions, while prototypal inheritance uses objects.
The prototype chain is a crucial concept in JavaScript inheritance. When a property or method is accessed on an object, JavaScript first checks if that object has that property or method. If it doesn’t, JavaScript then checks the object’s prototype. This process continues up the prototype chain until the property or method is found or the end of the chain is reached (which is usually the built-in Object prototype). This mechanism allows objects to inherit properties and methods from their prototypes, enabling code reuse and inheritance in JavaScript.
The ‘super’ keyword in JavaScript is used in the context of classes to call functions on an object’s parent. In other words, ‘super’ allows you to access and call functions on an object’s parent class, enabling you to reuse the parent class’s methods. This is particularly useful in the constructor of a subclass, where you might want to call the constructor of the parent class.
Overriding inherited methods in JavaScript is straightforward. You simply define a method with the same name in the child class or object. When that method is called on an instance of the child class or object, the version defined in the child will be used instead of the one in the parent. This allows you to customize or extend the behavior of inherited methods.
The ‘constructor’ in JavaScript is a special method that is used to create and initialize an object. In the context of inheritance, the constructor function of the parent class is often called in the constructor of the child class using the ‘super’ keyword. This allows the child class to inherit the properties and methods of the parent class.
With the introduction of ES6, JavaScript now has a more traditional class-based syntax for defining constructors and working with inheritance. The ‘class’ keyword is used to define a class, and the ‘extends’ keyword is used to create a subclass that inherits from a parent class. The ‘super’ keyword is used in the constructor of the subclass to call the constructor of the parent class.
JavaScript does not natively support multiple inheritance, where an object or class can inherit from more than one parent. However, it is possible to simulate multiple inheritance using mixins. A mixin is a technique where an object or class can “mix in” properties and methods from multiple sources. This allows you to combine the functionality of multiple objects or classes into one.
Inheritance and composition are two ways to reuse code in JavaScript. Inheritance is where an object or class inherits properties and methods from a parent object or class. Composition, on the other hand, is where an object is composed of other objects, and functionality is delegated to these component objects. While inheritance is about an “is-a” relationship (a subclass is a type of the parent class), composition is about a “has-a” relationship (an object has other objects).
Functions in JavaScript are objects, and they can be used to implement inheritance. This is done by defining a constructor function, which is used to create new objects. The ‘prototype’ property of the constructor function is an object that all instances of the function will inherit from. By adding properties and methods to this prototype object, you can make them available to all instances of the function.
One common pitfall of JavaScript inheritance is the confusion between the prototype chain and the constructor chain. When a method is called on an object, JavaScript looks up the prototype chain, not the constructor chain. Another pitfall is forgetting to call the parent constructor in the child constructor, which can lead to unexpected results. Finally, because JavaScript uses prototypal inheritance, it’s possible to accidentally modify the prototype when you meant to modify an instance.
The above is the detailed content of Simple Inheritance with JavaScript. For more information, please follow other related articles on the PHP Chinese website!