Some programming languages support object-oriented approaches natively by providing a feature to create an object instance based on a class
definition. Meanwhile, in Javascript, we know there is class
syntax, but it is just a kind of syntactic sugar that allows us to instantiate an object that can inherit some traits from another object or class definition in a similar fashion to other programming languages. In Javascript, a class is just a function with a prototype
property that maintain traits that can be passed down to other object instance. There are several ways to allow property inheritance in Javascript.
Functional
In this way, we utilize the Object.create()
method built in Javascript. The steps are:
- Create an object as the prototype provider.
- Pass the prototype provider to the
Object.create()
method along with additional properties declaration if needed.
For example,
const provider = { sum: (a, b) => a + b };
const obj = Object.create(
provider,
{ name: { value: 'My Object' } }
);
console.log(Object.getPrototypeOf(obj));
console.log(obj.sum(1,2));
console.log(obj.name);
Constructor Function
We can utilize the new
syntax to instantiate an object from a constructor function. The constructor function can inherit traits from another function by calling it. It is like calling the super()
method in a class-syntax way. The steps are:
- Declare a function as the ancestor function that maintains its own prototype properties.
- Declare a function that calls the ancestor function and will be instantiated as an object.
- Set the prototype inheritance using the
Object.setPrototypeOf()
function.
For example,
function Animal(name) {
this.name = name;
}
Animal.prototype.talk = function() {
console.log(`${this.name} is talking`);
}
function Chicken (name) {
Animal.call(this, name);
}
Chicken.prototype.fly = function() {
console.log(`${this.name} is flying`);
}
Object.setPrototypeOf(Chicken.prototype, Animal.prototype)
const chicken = new Chicken('Bob');
chicken.talk();
chicken.fly();
Class Syntax
This is the recommended way in modern Javascript. The syntax is very straightforward and looks very similar to other programming languages. What we should remember is that the extends
syntax is not for extending a class with another class directly but rather to patch the prototype chain. For example,
class Cat {
constructor(name) {
this.name = name;
}
meow() {
console.log(`${this.name} is meow`)
}
}
class Tiger extends Cat {
constructor(name) {
super(name + ' the Tiger');
}
}
const tiger = new Tiger('Bob');
tiger.meow();
Comments
Post a Comment