At this thread it is suggested that Object.getOwnPropertyNames
should return all properties of an object including functions. But when I do the following;
let date1 = new Date();
Object.getOwnPropertyNames(date1);
this returns 0 results. But date1
has methods like date1.toISOString()
.
How can I fetch all those methods?
CodePudding user response:
getOwnPropertyNames
returns - as it sounds - own property names. .toISOString
is not a method on the Date itself - it's a method on the prototype.
For the same reason, the below does not log method
.
class C {
method() {}
}
const c = new C();
console.log(Object.getOwnPropertyNames(c));
Rather, they're properties on the internal prototype of the object - Date.prototype
. So, call it on the prototype:
const date1 = new Date();
console.log(Object.getOwnPropertyNames(Date.prototype));
CodePudding user response:
Object.getOwnPropertyNames()
only returns the names of properties that the object owns and functions don't own any properties by default.
All of an object's methods are properties of its prototype, not the constructor function itself.
To answer your question, you can simply use Object.getOwnPropertyNames()
on the constructor function's prototype to get all of its methods. To access the object's prototype, use the Object.getPrototypeOf()
:
let date1 = new Date();
console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(date1)));
To further understand this, look at this example which creates a constructor function, a method, and a static method:
function A() {
console.log('constructor');
}
A.prototype.method = function() {
console.log('method');
}
A.staticMethod = function() {
console.log('staticMethod');
}
const obj = new A();
obj.method();
A.staticMethod();
const property_names = Object.getOwnPropertyNames(A);
console.log('Own property names: ', property_names);
const proto_property_names = Object.getOwnPropertyNames(Object.getPrototypeOf(obj));
console.log('Prototype\'s own property names: ', proto_property_names);
Static methods are stored in the function itself, so it is logged as the own property of the constructor function itself, while the methods are the own properties of the object's prototype.
ES6 Classes are also syntactic sugar for functions, so this works for classes too:
class A {
constructor() {
console.log('constructor');
}
method() {
console.log('method');
}
static staticMethod() {
console.log('staticMethod');
}
}
const obj = new A();
obj.method();
A.staticMethod();
const property_names = Object.getOwnPropertyNames(A);
console.log('Own property names: ', property_names);
const proto_property_names = Object.getOwnPropertyNames(Object.getPrototypeOf(obj));
console.log('Prototype\'s property names: ', proto_property_names);