A
regular JavaScript function can be called with the new keyword, for which the function behaves as a class constructor for creating new instance objects.
Code e.g:
function Square (length = 10) {
this.length = parseInt(length) || 10;
this.getArea = function() {
return Math.pow(this.length, 2);
}
this.getPerimeter = function() {
return 4 * this.length;
}
}
const square = new Square();
console.log(square.length); // 10
console.log(square.getArea()); // 100
Unlike regular functions,
arrow functions can never be called with the new keyword because they do not have the [[Construct]] method. As such, the prototype property also does not exist for arrow functions.
Sadly, that is very true. Arrow functions cannot be used as constructors. They cannot be called with the new keyword. Doing that throws an error indicating that the function is not a constructor.
Also, because arrow functions cannot be called with the new keyword, there is really no need for them to have a prototype. Hence, the prototype property does not exist for arrow functions.
Since the prototype of an arrow function is undefined, attempting to augment it with properties and methods, or access a property on it, will throw an error.
Code e.g:
const Square = (length = 10) => {
this.length = parseInt(length) || 10;
}
// throws an error
const square = new Square(5);
// throws an error
Square.prototype.getArea = function() {
return Math.pow(this.length, 2);
}
console.log(Square.prototype); // undefined