How to iterate over properties of a prototype object

I have a code:

var obj = function() { }; // functional object obj.foo = 'foo'; obj.prototype.bar = 'bar'; for (var prop in obj) { console.log(prop); } 

What surprised me was that all that was recorded was foo . I expected the for loop to iterate over the properties of the obj prototype (namely bar ), because I did not check hasOwnProperty . What am I missing here? And is there an idiomatic way to iterate over all the properties in a prototype?

I tested this in Chrome and IE10.

Thanks in advance.

+6
source share
2 answers

You repeat the constructor properties, you need to create an instance. An instance is what inherits from the prototype constructor property:

 var Ctor = function() { }; // constructor function Ctor.prototype.bar = 'bar'; var obj = new Ctor(); // instantiation // adds own property to instance obj.foo = 'foo'; // logs foo and bar for (var prop in obj) { console.log(prop); } 
+6
source

If you want to preserve the inheritance hierarchy by specifying all the properties before creating the object, you can follow the approach below. This approach prints a chain of prototype hierarchies.

Note. In this approach, you do not need to create a constructor first.

 function myself() { this.g = ""; this.h = []; this.i = {}; myself.prototype = new parent(); myself.prototype.constructor = myself; } function parent() { this.d = ""; this.e = []; this.f = {}; parent.prototype = new grandParent(); parent.prototype.constructor = parent; } function grandParent() { this.a = ""; this.b = []; this.c = {}; } var data = new myself(); var jsonData = {}; do { for(var key in data) { if(data.hasOwnProperty(key) && data.propertyIsEnumerable(key)) { jsonData[key] = data[key]; } } data = Object.getPrototypeOf(data).constructor.prototype; Object.defineProperties(data, { 'constructor': { enumerable: false } }); } while (data.constructor.name !== "grandParent") console.log(jsonData); 
0
source

Source: https://habr.com/ru/post/954526/


All Articles