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);