如何迭代对象的原型属性 [英] How to iterate over an object's prototype's properties

查看:158
本文介绍了如何迭代对象的原型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码:

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

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

让我感到惊讶的是,记录的所有内容都是 FOO 。我期望for循环也迭代 obj 的原型的属性(即 bar ),因为我没有检查 hasOwnProperty 。我在这里错过了什么?是否有一种惯用的方法来迭代原型中的所有属性?

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?

我在Chrome和IE10中对此进行了测试。

I tested this in Chrome and IE10.

提前致谢。

推荐答案

您正在迭代构造函数的属性,您必须创建一个实例。该实例继承自构造函数的 prototype 属性:

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); 
}

这篇关于如何迭代对象的原型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆