javaScript关于call的基础问题

cocotsau cocotsau 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
是这样的,我想给json对象扩展一个forEach方法,于是有了下面这段代码,功能是实现了,但是最后有个问题比较诡异,我想应该是出在call上面(代码第11行),在控制台打印,把函数体给输出来了。请大神帮忙看看,谢谢!

if (!Object.prototype.forEach) {
Object.prototype.forEach = function(fn) {
if ({}.toString.call(this) != "[object Object]") {
throw new TypeError();
}
if (typeof fn != "function") {
throw new TypeError();
}
for (var key in this) {
if(key in this){
fn.call(this, this[key], key, this);
//执行回调函数,并传入参数:值、索引、对象
}
}
}
}

var obj = {"a": 1,"b": 2};

obj.forEach(function(a,b,c){
console.log(a,b,c);
/*
1 "a" Object {a: 1, b: 2}
2 "b" Object {a: 1, b: 2}
-----------------------------------------------------------
//为什么会打印出函数体来?
function (fn) {
if ({}.toString.call(this) != "[object Object]") {
throw new TypeError();
}
if (typeof fn != "function") {
throw new TypeError();
}
for (var key in this) {
if(key in… "forEach" Object {a: 1, b: 2}
*/
})
...全文

相关推荐

评论 6
收藏 已收藏
分享
返回顶部
cocotsau
JavaScript 87,984 成员 224,680 内容