constructor - Javascript - List all properties/methods from an object -


i know object literal can have keys listed using object.keys() method. object created through constructor function?

function foo () {} foo.prototype.bar = 'bar'; foo.prototype.baz = 'baz';  var foo = new foo(); console.log(object.keys(foo).join(', ')); // returns '' console.log(object.getownpropertynames(foo).join(', ')); // returns '' 

object.keys own enumerable properties, , getownpropertynames own properties (even if not enumerable). neither of them give names of properties inherited prototype (or prototype, or its, ...).

if care enumerable properties, see trincot's answer.

if want all of them,¹ if they're not enumerable, have loop through prototype chain:

function getallpropertynames(obj) {    var result = [];    while (obj && obj !== object.prototype) {      result.push.apply(result, object.getownpropertynames(obj));      obj = object.getprototypeof(obj);    }    return result;  }    function foo () {}  foo.prototype.bar = 'bar';  foo.prototype.baz = 'baz';    var foo = new foo();  console.log(getallpropertynames(foo));

in example, stopped when reached object.prototype, of course keep going until hit null instead:

function getallpropertynames(obj) {    var result = [];    while (obj) {      result.push.apply(result, object.getownpropertynames(obj));      obj = object.getprototypeof(obj);    }    return result;  }    function foo () {}  foo.prototype.bar = 'bar';  foo.prototype.baz = 'baz';    var foo = new foo();  console.log(getallpropertynames(foo));


¹ "if want all of them..." note in above, haven't tried properties named symbols instead of strings. if did, we'd use getownpropertysymbols getownpropertynames.


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -