1

Getting available methods/properties for various types in javascript

To see the methods available to an object I am able to do:

console.log(Object.getOwnPropertyNames(Object));

But then why doesn't it give the properties when I pass it an instance of a particular object type (I hope that is the correct terminology?). For example, in the following n has one method called toFixed but it doesn't show up when trying to get the property names.

let n = 1234.567;
console.log(n.toFixed(1));
console.log(Object.getOwnPropertyNames(n));

Submitted October 09th 2021 by Admin

Answers
0

getOwnPropertyNames, as it sounds, gets only the own properties of the object.

But numbers are primitives, not objects - and toFixed is on Number.prototype, not on Number instances. The number has no own properties.

console.log(Object.getOwnPropertyNames(Number.prototype));

For another example, with a proper object:

class X { protoMethod(){}
}
const x = new X(); // Empty:
console.log(Object.getOwnPropertyNames(x));
// The prototype has the own-property of the method:
console.log(Object.getOwnPropertyNames(X.prototype));

Admin | 1 week ago


0

Try Object.getPrototypeOf. All the methods are defined in the prototype of the object.

console.log(Object.getPrototypeOf(n));

Admin | 1 week ago



Relevant Questions