Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
130
rated 0 times [  133] [ 3]  / answers: 1 / hits: 23062  / 9 Years ago, mon, may 11, 2015, 12:00:00

Is there any other way to look up for the prototype properties of an javascript object. Lets say I have like this.



function proton() {
this.property1 = undefined;
this.property2 = undefined;
};

proton.prototype = {

sample1 : function() {
return 'something';
},

sample2 : function() {
return 'something';
}

};

var my_object = new proton();

console.log(Object.keys(my_object));


returns [property1, property2]



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


returns [property1, property2]



But what i want to print is the prototype properties of the object my_object.



['sample1', 'sample2']



In order for me to see the prototype properties of that object i need to console.log(object) and from developer tools i can look up for the properties of that object.



But since I am using third party libraries like phaser.js, react.js, create.js
so i don't know the list of the prototype properties of a created object from this libraries.



Is there any prototype function of Object to list down all the prototpye properties of a javascript object?


More From » javascript

 Answers
3

Not a prototype method, but you can use Object.getPrototypeOf to traverse the prototype chain and then get the own property names of each of those objects.



function logAllProperties(obj) {
if (obj == null) return; // recursive approach
console.log(Object.getOwnPropertyNames(obj));
logAllProperties(Object.getPrototypeOf(obj));
}
logAllProperties(my_object);


Using this, you can also write a function that returns you an array of all the property names:



function props(obj) {
var p = [];
for (; obj != null; obj = Object.getPrototypeOf(obj)) {
var op = Object.getOwnPropertyNames(obj);
for (var i=0; i<op.length; i++)
if (p.indexOf(op[i]) == -1)
p.push(op[i]);
}
return p;
}
console.log(props(my_object)); // [property1, property2, sample1, sample2, constructor, toString, toLocaleString, valueOf, hasOwnProperty, isPrototypeOf, propertyIsEnumerable

[#66651] Friday, May 8, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
havenbilliec

Total Points: 324
Total Questions: 106
Total Answers: 94

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;