Home > Software engineering >  print foo by modifying the below piece of code
print foo by modifying the below piece of code

Time:01-06

Without hardcoding the string, 'foo', how can i modify the code above so that it prints out 'foo 1', 'foo 2', and 'foo 3' each on separate lines.

const obj = {
  x: 'foo',
  f: function() {
    [1, 2, 3].forEach(function(num) {
      console.log(this.x, num);
    });
  }
}

obj.f();

CodePudding user response:

Classic "function" declarations will bind to the caller's "this" environment instead of how most languages do it. Traditionally, this can be fixed with the bind method on a function as follows:

const obj = {
     x: 'foo',
      f: function() {
          [1, 2, 3].forEach(function(num) {
              console.log(this.x, num);
          }.bind(this))
        }
    };

The simpler approach is to just use the new arrow syntax, which will bind the function as you would naturally expect.

This line:

[1, 2, 3].forEach(function(num) {

To this:

[1, 2, 3].forEach((num)=> {

CodePudding user response:

const obj = {
  x: 'foo',
  f: function() {
    [1, 2, 3].forEach(function(num) {
      console.log(`${obj.x} ${num}`);
    });
  }
}

obj.f();
  •  Tags:  
  • Related