对于数组诸多方法,指定this时的使用

诸如:filter,every,some,forEach… 他们都是接收两个参数的,一个是函数,一个是this指向。

第一个参数是函数,这个函数接收的参数是(key,value,array)

对于第二个参数this指向其实一致用的是很少的:

const map = new Map([[1,'1'],[2,'2'],[3,'3'],[4,'4'],[5,'5']])
const reporter = {
    
    
  report: function(key, value) {
    
    
    console.log("Key: %s, Value: %s", key, value);
  }
};
map.forEach(function(value, key, map) {
    
    
  console.log(this)
  this.report(key, value);
}, reporter)

// { report: [Function: report] }
// Key: 1, Value: 1
// { report: [Function: report] }
// Key: 2, Value: 2
// { report: [Function: report] }
// Key: 3, Value: 3
// { report: [Function: report] }
// Key: 4, Value: 4
// { report: [Function: report] }
// Key: 5, Value: 5

猜你喜欢

转载自blog.csdn.net/weixin_43131046/article/details/125684392