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.
You combine the two, and it pretty much explains why this doesn't work the
way a lot of people think it should:
obj.foo = functionfoo() {
setTimeout(functionbar() {
// `this` is bar's context, not foo'sthis.doSomething();
// `arguments` is bar's arguments, not foo'svar args = [].slice.call(arguments);
}, 0);
}
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);
}
```
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150728/117fcfb4/attachment.html>
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.
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]
arguments
object, independent of any closure.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:
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); }