0

Why does 7 line return object window?

Why not a sport object?

var sport = {
caption: "2017",
players :  [{"name":"cat"},{"name":"dog"}] ,
show: function() {
  this.players.forEach(function(entry) {
      console.log(entry.name);
      console.log(this);//window
  });
}
}

sport.show();

https://jsfiddle.net/6qkj2byk/

enot
  • 141
  • 1
  • 8
  • 2
    Use arrow function. – kind user Apr 25 '17 at 21:39
  • 2
    The scope of this depends on the execution context and is late-bound. Search SO and the web and you'll find much discussion regarding this. – Dave Newton Apr 25 '17 at 21:40
  • 2
    "If a thisArg parameter is provided to forEach(), it will be used as callback's this value. Otherwise, the value undefined will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function." - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach – Nayuki Apr 25 '17 at 21:41
  • `"use strict";` – Gqqnbig Apr 25 '17 at 21:43
  • Why would it be the `sport` object and not the `sport.players` array? – Bergi Apr 25 '17 at 21:45

1 Answers1

1

this refers to the scope of the anonymous function in which it resides, which would be window.

var sport = {
  players: [1, 2, 3],
  show: function() {
    this.players.forEach(function(entry) {
      console.log(entry);
      
      // this refers to the scope of the anonymous function, which is window
      console.log(this);
    });
  }
}

//sport.show();


var sport2 = {
  players: [3, 4, 5],
  show: function() {

    // this refers to the object scope in which it resides - 
    // in which case, that would be "sport2"
    var self = this;
    this.players.forEach(function(entry) {
      console.log(entry);

      // self is now synonymous with "this" in the sport2 scope.
      console.log(self);
    });
  }
}

sport2.show();

Edit: self could be set inside of the show function itself, no need to pass it in the ugly way. Thanks to the comment section for pointing this out.

Danny Bullis
  • 3,043
  • 2
  • 29
  • 35