MENU
Prototype VS Static, Getter, Setter
RESETRUNFULL
<!DOCTYPE html><html><body><script>
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 variableAnimal.prototype.drink = function(){console.log(this.name+' is drinking.');} // prototype methodAnimal.message = 'We should protect all animals.'; // static variableAnimal.comment2 = ()=>console.log(Animal.message); // static methodvar b = new Animal('Brownie',5);console.log(b.age,b.sex); // 5 "m"b.eat(); // Brownie is eating.b.drink(); // Brownie is drinking.b.whoami(); // All animals are cute. I am a nice Animal.Animal.comment(); // All animals are cute.Animal.comment2(); // We should protect all animals.console.log(b.intro); // This is Brownie.b.rename='Greenie';b.drink(); // Greenie is drinking.console.log(typeof b); // object console.log(b instanceof Animal); // true//let m1=b.eat; m1(); // TypeError ('this' is undefined)let m2=Animal.comment; m2(); // All animals are cute.
</script></body><html>
Note how you verify the class name of an object with instanceofinstanceof instanceof .
A class declaration is not hoisted, ie. a class cannot be used before its declaration. Also, a class cannot be redeclared.