MENU
Prototype VS Static, Getter, Setter
class Animal {
constructor(n, a) {
this.name = n; // prototype variable
this.age = a; // prototype variable
}
eat() { // prototype method
console.log(this.name + ' is eating.');
}
static comment() { // static method
console.log('All animals are cute.');
}
whoami() {
//this.constructor.eat(); // TypeError
this.constructor.comment(); // this.constructor.staticFunction() allowed
console.log('I am a nice ' + this.constructor.name + '.');
}
get intro() { // getter, to act like prototype variable
return 'This is ' + this.name + '.';
}
set rename(n) { // setter
this.name = n;
}
}
Animal.prototype.sex = 'm'; // prototype variable
Animal.prototype.drink = function() {
console.log(this.name + ' is drinking.');
}; // prototype method
Animal.message = 'We should protect all animals.'; // static variable
Animal.comment2 = () => console.log(Animal.message); // static method
var b = new Animal('Brownie', 5);
console.log(b.age, b.sex);
b.eat();
b.drink();
b.whoami();
Animal.comment();
Animal.comment2();
console.log(b.intro);
b.rename = 'Greenie';
b.drink();
console.log(typeof b);
console.log(b instanceof Animal);
//let m1=b.eat; m1(); // TypeError ('this' is undefined)
let m2 = Animal.comment;
m2();5 "m"
Brownie is eating.
Brownie is drinking.
All animals are cute.
I am a nice Animal.
All animals are cute.
We should protect all animals.
This is Brownie.
Greenie is drinking.
object
true
All animals are cute.
Note how you verify the class name of an object with instanceof.
A class declaration is not hoisted, ie. a class cannot be used before its declaration. Also, a class cannot be redeclared.