Home > Software design >  Getting available methods/properties for various types in javascript
Getting available methods/properties for various types in javascript

Time:10-09

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

CodePudding user response:

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

CodePudding user response:

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

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