In JavaScript, the conventional appproach to creating object instances involves using constructor functions.
function Animal(name, age) {
this.name = name;
this.age = age;
}
Animal.prototype.showName = function() {
console.log(this.name);
console.log(this.age);
};
var instance = new Animal('Buddy', 4);
instance.showName();
This syntax differs significantly from traditional object-oriented languages like C++ or Java, potentially confusing developers new to JavaScript.
ES6 introduced a more familiar syntax through the class keyword, providing a template for objects. Essentially, ES6's class is syntactic sugar over ES5's prototype-based approach, offering cleaner syntax that resembles classical object-oriented programming. The previous example can be rewritten using ES6 classes as follows:
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
showName() {
console.log(this.name);
}
}
const animalInstance = new Animal('Max', 2);
The above defines a class with a constructor method, which initializes object properties upon instantiation. The this keyword refers to the created instance. In essence, ES5's constructor function Animal maps directly to the constructor method of the ES6 Animal class.
Beyond the constructor, the Animal class includes a showName method. Note that method definitions within a class do not require the function keyword; they are defined directly. Also, methods should not be separated by commas, as this would cause an error.
ES6 classes can be regarded as an alternative notation for constructor functions.
console.log(Animal === Animal.prototype.constructor); // true
This demonstrates that a class directly references its constructor function.
Instantiation uses the new operator, identical to constructor function usage.
Constructor Method
The constructor method serves as the default method invoked when creating an object instance via new. Every class must define a constructor, though if omitted, an empty one will be automatically added.
class Animal {}
// Is equivalent to
class Animal {
constructor() {}
}
In this case, JavaScript automatically inserts an empty constructor method into the Animal class.