// <<< using class syntax >>>
class Person {
constructor(name) {
this.name = name;
}
say() {
console.log(`Hello, ${this.name}`);
}
}
// <<< using function syntax >>>
'use strict'; // class syntax is strict mode by default
// call new on function is equivalent to create an object with the function as constructor
function Person(name) {
// constructor cannot be called without 'new'
if (!(this instanceof Person)) {
throw new TypeError("Class constructor Person cannot be invoked without 'new'");
}
this.name = name;
}
// class function is not enumerable by default,
// so we need to set enumerable to false.
Object.defineProperty(Person.prototype, 'say', {
value: function() {
// this must be an 'instance' of Person
if (!(this instanceof Person)) {
throw new TypeError("function say is not a constructor");
}
console.log(`Hello, ${this.name}`);
},
enumerable: false,
});