New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why forEach callback's this is window? #1213

Closed
BlackHole1 opened this Issue Jun 4, 2018 · 1 comment

Comments

Projects
None yet
3 participants
@BlackHole1

BlackHole1 commented Jun 4, 2018

[1,2,3].forEach(function () {
  console.log(this)
}) //=> window x 3

Whether the second parameters are empty or null or undefined, the this result is window.

I don't think it's wise. I think it should be like this:

[1,2,3].forEach(function () {
  console.log(this)
}) //=> Array(3) [1, 2, 3] x 3

Here's my Polyfill:

Array.prototype.forEach = function (callback, thisArg) {
  var callbackSelf, thisObj, i = 0, len

  if (this == null) {
    return new TypeError('this not defined')
  }
  if (typeof callback !== 'function') {
    return new TypeError(callback + 'is not function')
  }

  thisObj = Object(this)
  callbackSelf = thisArg || thisObj
  len = thisObj.length >>> 0

  while (i < len) {
    if (i in thisObj) {
      callback.call(callbackSelf, thisObj[i], i, thisObj)
    }
    i++
  }
}
@claudepache

This comment has been minimized.

Show comment
Hide comment
@claudepache

claudepache Jun 4, 2018

Contributor

I don't think it's wise.

Neither do I, but it is what you get when a function is called without this-value, and forEach is not different from other methods that existed since the dawn of JavaScript.

If you want a wiser behaviour, use strict mode: you’ll get undefined (or null).

(And if you want a reference to the array, use the third parameter of the callback.)

Contributor

claudepache commented Jun 4, 2018

I don't think it's wise.

Neither do I, but it is what you get when a function is called without this-value, and forEach is not different from other methods that existed since the dawn of JavaScript.

If you want a wiser behaviour, use strict mode: you’ll get undefined (or null).

(And if you want a reference to the array, use the third parameter of the callback.)

@ljharb ljharb added the question label Jun 4, 2018

@ljharb ljharb closed this Jun 4, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment