循环内部如何引用外层主this?解决forEach中this指向及数组转字符串问题
解决forEach循环中正确引用外层this的问题
你猜的没错!在普通function作为forEach回调的时候,它内部的this确实不会指向你的类实例,而是取决于forEach的调用上下文(这里就是数组本身,严格模式下甚至是undefined),所以才会出现this.properties变成undefined的情况。给你几个常用的解决办法:
方法一:使用箭头函数(最推荐)
箭头函数不会绑定自己的this,它会继承外层作用域的this,也就是你的类实例。修改后的代码如下:
listProperties() { this.properties = ""; this.state.withoutSuit.forEach((i, j) => { this.properties += i; this.properties += " "; }); console.log(this.properties); return this.properties; }
方法二:提前保存外层的this到变量
在forEach之前,把外层的this存到一个变量里(比如常用的that、self),然后在回调里用这个变量:
listProperties() { this.properties = ""; const that = this; // 保存外层this this.state.withoutSuit.forEach(function (i, j) { that.properties += i; that.properties += " "; }); console.log(this.properties); return this.properties; }
方法三:利用forEach的第二个参数指定this
forEach方法本身支持第二个参数,用来指定回调函数执行时的this指向:
listProperties() { this.properties = ""; this.state.withoutSuit.forEach(function (i, j) { this.properties += i; this.properties += " "; }, this); // 这里传入外层的this,指定回调的this指向 console.log(this.properties); return this.properties; }
另外,顺便提一句,你现在的写法最后会多一个末尾空格,如果想避免的话,可以直接用数组的join方法,一行就能搞定,更简洁高效:
listProperties() { this.properties = this.state.withoutSuit.join(" "); console.log(this.properties); return this.properties; }
join(" ")会自动把数组元素用空格连接,而且不会在最后多出一个空格,比循环拼接更省心~
内容的提问来源于stack exchange,提问作者user43107
相关产品推荐
相关产品推荐

