carl.hiass
carl.hiass

Reputation: 1774

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

Upvotes: 1

Views: 51

Answers (2)

sgqbjanmoxzdozlprr
sgqbjanmoxzdozlprr

Reputation: 17

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

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

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370789

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

Upvotes: 3

Related Questions