js原型链中的函数为什么可以用for in来遍历

如题所述

1.原型链:

    当前对象a=new A()的原型(._proto_)是当前构造函数A.prototype.

    A.prototype又可能是另一个构造函数B的实例(new B()).

    new B()._proto_是当前构造函数B.prototype又可能是构造函数C的实例.

    如此向上找形成原型链.


2 for..in

    可以遍历可枚举属性(自有属性和继承属性).

    所谓继承属性就和原型链息息相关.

    如上a继承了构造函数A.prototype里的方法和属性.

    A.prototype又继承了B.prototype的方法和属性.

    B.prototype又继承了C.prototype的方法和属性.如此往复.

3.例子

function A(){ this.a="a" }

function B(){ this.b="b" }

B.prototype=new A();

var a=new B();

for(var k in a){ console.log("属性"+k+": 值"+a[k]) }

4.控制台


温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-02-04

Enumerable 特性

属性特性 enumerable 定义了对象的属性是否可以在 for...in 循环和 Object.keys() 中被枚举。

var o = {};
Object.defineProperty(o, "a", { value : 1, enumerable:true });
Object.defineProperty(o, "b", { value : 2, enumerable:false });
Object.defineProperty(o, "c", { value : 3 }); 
// enumerable defaults to false
o.d = 4; 
// 如果使用直接赋值的方式创建对象的属性,
// 则这个属性的enumerable为true
for (var i in o) {    
  console.log(i);  
}
// 打印 'a' 和 'd' (in undefined order)
Object.keys(o); // ["a", "d"]
o.propertyIsEnumerable('a'); // true
o.propertyIsEnumerable('b'); // false
o.propertyIsEnumerable('c'); // false

遍历至某属性时,如果值为undefined,则会沿原型链查找,如果找到该值并且enumerable为true,就会被遍历到

第2个回答  2016-09-29
因为原型连里面的任何东西,不管是属性还是函数,都是这个原型对象的属性
相似回答