I am wondering what's the difference between function and class. Both using the keyword function, is there obvious distinction between those two?
I am wondering what's the difference between function and class. Both using the keyword function, is there obvious distinction between those two?
function and classThe class keyword in javascript is very similar to a constructor function in the following manner:
new myObj(arg1, arg2)Constructor functions and classes are very alike can often be used interchangeably based on preference. However, javascript's private fields to classes is functionality which cannot be implemented by constructor functions (without scope hacks)
class PersonClass {
constructor(name) {
this.name = name;
}
speak () { console.log('hi'); }
}
console.log(typeof PersonClass);
// logs function, a class is a constructor function under the hood.
console.log(PersonClass.prototype.speak);
// The class's methods are placed on the prototype of the PersonClass constructor function
const me = new PersonClass('Willem');
console.log(me.name);
// logs Willem, properties assinged in the constructor are placed on the newly created object
// The constructor function equivalent would be the following:
function PersonFunction (name) {
this.name = name;
}
PersonFunction.prototype.speak = function () { console.log('hi'); }