My understanding was that all classes were essentially functions, and all instances were essentially objects. But something confused me.
//Take this for example:
function AnimalFunc(name) {
this.name = name;
this.sayName = function() {
console.log(this.name);
}
}
//And compare it with this:
class AnimalClass {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}
//Now I instantiate them.
cat = new AnimalFunc("cat")
cat.sayName() // -> "cat"
dog = new AnimalClass("dog")
dog.sayName() // -> "dog"
console.log(Object.keys(cat));
console.log(Object.keys(dog));
Expected Observations:
typeof(AnimalClass)
andtypeof(AnimalFunc)
both returnfunction
.typeof(cat)
andtypeof(dog)
both returnobject
.
Unexpected Observations:
- If I do
Object.keys(cat)
, I get["name","sayname"]
. - But if I do
Object.keys(dog)
, I get["name"]
.
My question is: why do I not get sayname
as a key for the class instance? Why do I get it only for the function instance?