Javascript - 1、forEach用法及this的一点小引申
forEach最常用的用法
[3,4,5].forEach((e,idx)=>{ console.log(e,idx); })
一般有三种写法
(1)回调函数写法
forEach(callbackFn)
forEach(callbackFn, thisArg)
(2)箭头函数写法【此法无thisArg的用法】
forEach((element) => { /* … */ }) 元素
forEach((element, index) => { /* … */ }) +索引
forEach((element, index, array) => { /* … */ }) +当前数组
forEach((element, index, array) => { /* … */ },thisArg) 这里的thisArg不会传递给函数体从而作为函数中的this,函数中的this指向上一级的对象
(3)内联回调函数的写法
forEach(function(element) { /* … */ })
forEach(function(element, index) { /* … */ })
forEach(function(element, index, array){ /* … */ })
forEach(function(element, index, array) { /* … */ }, thisArg)
注意thisArg这个参数:
(1)thisArg在箭头函数中无效,this指向函数上一级的对象。很多人说指向window,其实是不准确的。如下例(1)(2)
(2)在非箭头函数中,如果 thisArg 参数有值,则每次 callback 函数被调用时,this 都会指向 thisArg 参数。如果省略了 thisArg 参数,或者其值为 null 或 undefined,this 则直接指向window,不传导。如例子(3)
例子(1)
let a ={ sum:function(){ [3].forEach(()=>{console.log(this)}) } }; a.sum();//输出a对象
例子(2)
let a ={ sum:()=>{ [3].forEach(()=>{console.log(this)}) } }; a.sum();//输出window对象。这是由于上一级也是箭头函数,所以继续向上传导
例子(3)
let a ={ sum:function(){//这里如果是箭头函数,也是输出window [3].forEach(function(){console.log(this)}) } }; a.sum();//输出window
如果要在例子(3)中,让函数里可以使用this,那么就可以使用bind(this)。这样就可以得到例(4)(5)
例子(4)
let a ={ sum:function(){ [3].forEach(function(){console.log(this)}.bind(this)) } }; a.sum();//输出对象a
例子(5)
let a ={ sum:()=>{ [3].forEach(function(){console.log(this)}.bind(this)) } }; a.sum();//输出对象window,因为箭头函数不捕获this,继续传导。
thisArg小总结: forEach中,箭头函数不捕获thisArg参数,继续传导。function(){}形式的函数,捕获thisArg参数;但如果thisArg为null、空、undefined,则函数体的this直接为window。//这里“捕获”这个词是笔者自己的理解,非专业术语