vscode showing different methods, properties and events
Hey people,
I can see that in vscode it is possible to see all the different properties, methods and events of a given object. How can I access all of these and store them in an array, without having to hardcode it?
CodePudding user response:
Object.keys(obj)
will give you an array of the enumerable properties on the object.
Object.getOwnPropertyDescriptors(obj)
will give you an array of "own" property descriptors for the object and will include non-enumerable properties.
Object.getOwnPropertyNames(obj)
will gives you an array of "own" property names for the object and will include non-enumerable properties.
If you want to also list what methods might be on the prototype, then you'd have to use one of these above methods on the prototype which you can get with Object.getPrototypeOf(obj)
.
And, if this object is a subclass and you want to include methods on any base classes, you'd have to follow the prototype chain and enumerate each prototype in that chain. You follow the chain by calling Object.getPrototypeOf(obj)
and then call that again on that prototype and so on until you get null
. This is how you "walk" the prototype chain.
You can see the MDN doc for all of these for more info.
Here's an example:
class A {
constructor() {
this.propA = "A";
Object.defineProperty(this, "propA2", { enumerable: false });
}
showMe() {
console.log("I'm from class A");
}
}
class B extends A {
constructor() {
super();
this.propB = "B";
Object.defineProperty(this, "propB2", { enumerable: false });
}
showMeToo() {
console.log("I'm from class B");
}
}
let x = new B();
// [ 'propA', 'propB' ]
console.log(Object.keys(x));
// [ 'propA', 'propA2', 'propB', 'propB2' ]
console.log(Object.getOwnPropertyNames(x));
// [ 'constructor', 'showMeToo' ]
let protoB = Object.getPrototypeOf(x);
console.log(Object.getOwnPropertyNames(protoB));
// [ 'constructor', 'showMe' ]
let protoA = Object.getPrototypeOf(protoB);
console.log(Object.getOwnPropertyNames(protoA));
// shows properties on generic Object prototype
let p1 = Object.getPrototypeOf(protoA);
console.log(Object.getOwnPropertyNames(p1));
// shows null because it's the end of the prototype chain
let p2 = Object.getPrototypeOf(p1);
console.log(p2);
CodePudding user response:
You can use Object.keys(yourObj)
This returns all properties of a given object.