How to function call using 'this' inside forEach loop

后端 未结 2 1963
南方客
南方客 2020-12-13 03:41

In the following object, I have a problem using the \'this\' reference:

function SampleObject(){
    this.addObject = function(object){...}
    ...
    // mo         


        
2条回答
  •  孤城傲影
    2020-12-13 04:30

    const array1 = [
      {name : "john", age: 20}, {name : "sarah", age: 70}
      ];
    
    array1.forEach(element => this.print(element));
    
    print = (data) =>
    {
      console.log(data.name);
    }
    // expected output: "john"
    // expected output: "sarah"

    There is better way to do this

    array.forEach(obj => this.functionName(params));

提交回复
热议问题