对象实现`for of`,`Object.keys(Object(this))`这里面的`this`是什么?-灵析社区

我是张工你呢

`Object.keys(Object(this))`这里面的`this`是什么?为什么`value`值输出为`undefined`? ![image.png](https://wmprod.oss-cn-shanghai.aliyuncs.com/images/20250103/41043c97ad4844a57b0ca0f319ad97a6.png) const obj = { a: 1, b: 2, c: 3 } Object.prototype[Symbol.iterator] = function value() { console.log("this-------", this,Object(this)); const keys = Object.keys(Object(this)); let nextIndex = 0; function next() { return nextIndex < keys.length ? { value: [keys[nextIndex], obj[keys[nextIndex++]]], done: false } : { value: undefined, done: true }; } return { next } } for (const [key, value] in obj) { console.log('key----', key); console.log('value----', value); }

阅读量:360

点赞量:9

问AI
东三环
this就是 obj,至于为什么不对 是因为你用的for in 而不是 for of, for...in循环用于遍历对象的可枚举属性。它遍历对象自身及其原型链上的所有可枚举属性,但不会遍历对象的迭代器