如何将上下文传递给 forEach() 匿名函数 [英] How to pass context to forEach() anonymous function

查看:33
本文介绍了如何将上下文传递给 forEach() 匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

this 上下文传递给匿名 forEach 函数的现代正确方法是什么?

What's the modern and correct way to pass the this context to an anonymous forEach function?

function Chart() {

  this.draw = function(data) {
     data.forEach(function(value) {
       //do something with values
       console.log(this); //question: how to get Chart instead of global scope?
     )};
  });

};

推荐答案

将当前的this存储在Chart中的其他变量中

Store the current this in some other variable in Chart like this

function Chart() {
    var self = this;
    this.draw = function(data) {
        data.forEach(function(value) {
            //do something with values
            console.log(self);
        });
    }
};

此外,您可以像下面这样传递this,如Array.prototype.forEach 接受 this

Also, you can pass the this like the following, as Array.prototype.forEach accepts this

arr.forEach(callback[, thisArg])

例如

this.draw = function(data) {
    data.forEach(function(value) {
        //do something with values
        console.log(this);
    }, this); // Pass the current object as the second parameter
}

这篇关于如何将上下文传递给 forEach() 匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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