Is my understanding correct in this scope generalization of pre-ES6
functions? I know a lot of people never really understood scoping,
especially in ES5, very well, but I got thinking and found it seemed
incredibly simple.

- Each function has its own context, independent of any closure.

```js
function foo() {
  function bar() {
    console.log(this);
  }

  bar(); // undefined
  bar.call({}); // [object Object]
  bar.call(this); // <this>

  console.log(this)
}

foo(); // undefined
foo.call({}); // [object Object]
```

- Each function has its own `arguments` object, independent of any closure.

```js
function foo() {
  function bar() {
    return [].slice.call(arguments);
  }

  bar(); // []
  bar(2); // [2]
  bar.apply(null, arguments); // <arguments>

  return [].slice.call(arguments);
}

foo(); // []
foo(3); // [3]
```

You combine the two, and it pretty much explains why this doesn't work the
way a lot of people think it should:

```js
obj.foo = function foo() {
  setTimeout(function bar() {
    // `this` is bar's context, not foo's
    this.doSomething();

    // `arguments` is bar's arguments, not foo's
    var args = [].slice.call(arguments);
  }, 0);
}
```
_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to