Javascript 在JS中通过div运行forEach()会产生错误
我想更改数组中的几个div的高度,即使我记录了div的名称并给出了正确的对象名称,我仍然会在控制台中收到一条“this is undefined”错误消息 就像我说的,当我注销所有正确给出的div名称时,但是在我想设置其高度的行上,我猜“this”在某个地方有问题Javascript 在JS中通过div运行forEach()会产生错误,javascript,angular,Javascript,Angular,我想更改数组中的几个div的高度,即使我记录了div的名称并给出了正确的对象名称,我仍然会在控制台中收到一条“this is undefined”错误消息 就像我说的,当我注销所有正确给出的div名称时,但是在我想设置其高度的行上,我猜“this”在某个地方有问题 this.divs.forEach(names); function names(div) { console.log(div); //goes thought all the divs correctly
this.divs.forEach(names);
function names(div) {
console.log(div); //goes thought all the divs correctly
this._renderer.setElementStyle(div.nativeElement, 'height', largestHeight + 'px');
}
我正在用angular2做这件事,以防有人想知道。
谢谢你的帮助 问题就在这里
function names(div) {
在JavaScript中,这属于当前函数,除非您传递另一个this
:
this.divs.forEach(names.bind(this));
或者在ES6中
let names = (div) => {
console.log(div); //goes thought all the divs correctly
this._renderer.setElementStyle(div.nativeElement, 'height', largestHeight + 'px');
}
函数上下文中没有此,请尝试使用箭头函数:
this.divs.forEach((names) => {
...
});
您还可以将此绑定到您的函数
this.divs.forEach(names.bind(this));
也许可以尝试使用forEach(names.bind(this)),这看起来像是一个范围问题。谢谢,回答与其他一样正确。谢谢allot,因为它是行中的第一个,所以标记为正确。:)@阿尔法“很多”“分配”的意思是“分配”。谢谢你的解释,它有助于分配,我会详细阅读。