array.forEach的thisArg不按预期引用 [英] thisArg of array.forEach does not reference as expected

查看:204
本文介绍了array.forEach的thisArg不按预期引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

  const theArray = ['Audi','Volvo','Mercedes']; 

const myObj = {a:7};

theArray.forEach((value,index,array)=> {
console.log(index +':'+ value);
console.log(array = == theArray);
console.log(this.a);
},myObj);

我得到以下输出:

<$ p $奥迪

undefined
1:沃尔沃


2:奔驰
true
undefined

在这里我不明白为什么 code>不引用myObj,并返回undefined而不是7.
这个类型的Object 返回true,我不知道它引用了哪个对象。我只知道这个返回一个空的Object(即{})

Node.js解释器版本是v6。 2.1 b
$ b V8-Engine版本是5.0.71.52

解决方案

问题



箭头函数


箭头函数表达式函数表达式和词法相比,语法较短绑定 这个 值(不绑定自己的 这个 arguments super ,或者 new.target )。箭头功能总是匿名

解决方案1 ​​

$ c $ function

$ b $ p

const theArray = [ 'Audi','Volvo','Mercedes']; const myObj = {a:7}; theArray.forEach(function(value,index,array){console.log(index +':'+ value); console。 log(array === theArray); console.log(this.a);},myObj);



解决方案2

使用闭包

<

  var abc ='abc'; const theArray = ['Audi','Volvo','Mercedes']; const myObj = {a:7}; theArray.forEach((obj => (value,index,array)=> {console.log(index +':'+ value); console.log(array === theArray);的console.log(obj.a); console.log(this.abc);})(myObj));  

Given following code:

const theArray = ['Audi','Volvo','Mercedes'];

const myObj = {a: 7};

theArray.forEach((value, index, array) => {
    console.log(index + ' : ' + value);
    console.log(array === theArray);
    console.log(this.a);
}, myObj);

I get following output:

0 : Audi
true
undefined
1 : Volvo
true
undefined
2 : Mercedes
true
undefined

Where I don't understand why this does not reference myObj and returns undefined instead of 7. While this typeof Object returns true, I don't know which Object it references. I just know that this returns an empty Object(i.e. {})

Node.js interpreter version is v6.2.1

V8-Engine version is 5.0.71.52

解决方案

Problem

Arrow functions:

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous.

Solution 1

Use function

const theArray = ['Audi','Volvo','Mercedes'];

const myObj = {a: 7};

theArray.forEach(function (value, index, array) {
    console.log(index + ' : ' + value);
    console.log(array === theArray);
    console.log(this.a);
}, myObj);

Solution 2

Use a closure

var abc = 'abc';
const theArray = ['Audi','Volvo','Mercedes'];

const myObj = {a: 7};

theArray.forEach((obj => (value, index, array) => {
    console.log(index + ' : ' + value);
    console.log(array === theArray);
    console.log(obj.a);
    console.log(this.abc);
})(myObj));

这篇关于array.forEach的thisArg不按预期引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆