How to iterate over an object's prototype'

2019-06-19 01:22发布

I have some code:

var obj = function() { }; // functional object
obj.foo = 'foo';
obj.prototype.bar = 'bar';

for (var prop in obj) {
    console.log(prop);
}

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

I tested this in Chrome and IE10.

Thanks in advance.

2条回答
走好不送
2楼-- · 2019-06-19 01:38

If you want to maintain an inheritance hierarchy by defining all the properties even before the object instantiation, you could follow the below approach. This approach prints the prototype hierarchy chain.

Note: In this approach you don't have to create the constructor initially.

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);
查看更多
在下西门庆
3楼-- · 2019-06-19 01:41

You're iterating over the constructor's properties, you have to create an instance. The instance is what inherits from the constructor's prototype 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); 
}
查看更多
登录 后发表回答