Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

for in 为什么不遍历对象原型上固有属性?

var triangle = { a: 1, b: 2, c: 3 };

Object.setPrototypeOf(triangle, { l: function add() {} });

function ColoredTriangle() {
  this.color = "red";
}

ColoredTriangle.prototype = triangle;

var obj = new ColoredTriangle();

for (var prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}

输出:
obj.color = red
obj.a = 1
obj.b = 2
obj.c = 3
obj.l = function add() {}

我们自定义的原型属性被打印了,但是对象的原型链上还有很多属性,为什么这些属性没被打印,难道是故意这么设计的?
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

设计如此。

Iterating over own properties only.

for...in - JavaScript | MDN (mozilla.org)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...