EN
JavaScript - how to get object's methods?
1 answers
0 points
Is there a method or property to get all methods from an object?
I need something like this:
xxxxxxxxxx
1
var myObject = {};
2
3
myObject.prototype.method1 = function() {};
4
myObject.prototype.method2 = function() {};
5
6
myObject.getMethods(); // Expected output: ['method1', 'method2'];
1 answer
0 points
With the solution below you can get all methods that are non-static or defined by user if you know the type or if you have an object that is based on some type (e.g. new Object
or class created with function()
).
xxxxxxxxxx
1
function collectMethods(methods, object) {
2
var keys = Object.keys(object);
3
for (var i = 0; i < keys.length; ++i) {
4
var key = keys[i];
5
if (key !== 'constructor' && typeof object[key] === 'function') {
6
methods.push(key);
7
}
8
}
9
}
10
11
function getMethods$1(object, methods) {
12
if (methods == null) {
13
methods = [];
14
}
15
var prototype = Object.getPrototypeOf(object);
16
if (prototype) {
17
getMethods$1(prototype, methods);
18
collectMethods(methods, prototype);
19
}
20
return methods;
21
}
22
23
function getMethods$2(clazz, methods) {
24
if (methods == null) {
25
methods = [];
26
}
27
var prototype = clazz.prototype;
28
if (prototype) {
29
getMethods$1(prototype, methods);
30
collectMethods(methods, prototype);
31
}
32
return methods;
33
}
34
35
36
// Usage example:
37
38
function ParentClass() {}
39
40
ParentClass.prototype.a = function() {};
41
ParentClass.prototype.b = function() {};
42
43
function SomeClass() {}
44
45
SomeClass.prototype = new ParentClass(); // inheritance from ParentClass
46
SomeClass.prototype.c = function() {};
47
SomeClass.prototype.d = function() {};
48
49
var someObject = new SomeClass();
50
51
console.log(getMethods$1(someObject));
52
console.log(getMethods$2(SomeClass));
0 commentsShow commentsAdd comment