Found answer here: Javascript what is property in hasOwnProperty?
In this post How to display all methods of an object?, it said "You can use Object.getOwnPropertyNames() to get all properties that belong to an object, whether enumerable or not". And with the example we can see all the properties includes methods of the Math
object listed. I tried and got the same result.
Then I tried to define my own object and list it's properties in the same way, but why the methods are not listed? e.g. For console.log(Object.getOwnPropertyNames(animal))
why it only returns ["name", "weight"]
but not includes "eat", "sleep" and wakeUp
?
function Animal(name, weight) {
this.name = name;
this.weight = weight;
}
Animal.prototype.eat = function() {
return `${this.name} is eating!`;
}
Animal.prototype.sleep = function() {
return `${this.name} is going to sleep!`;
}
Animal.prototype.wakeUp = function() {
return `${this.name} is waking up!`;
}
var animal = new Animal('Kitten', '5Kg');
console.log(Object.getOwnPropertyNames(animal)); // ["name", "weight"]
And another example is, why the following one returns the property which belongs to the super class, as it's Triangle
inherited from Shape
. For console.log(Object.getOwnPropertyNames(triangle));
do we suppose only get ["a", "b", "c"]
without "type"
?
class Shape {
constructor(type) {
this.type = type;
}
getType() {
return this.type;
}
}
class Triangle extends Shape {
constructor(a, b, c) {
super("triangle");
this.a = a;
this.b = b;
this.c = c;
}
getParamiter() {
return this.a + this.b + this.c;
}
}
const triangle = new Triangle(1,2,3);
console.log(Object.getOwnPropertyNames(triangle)); //["type", "a", "b", "c"]