ES5 functions
Isiah Meadows
impinball at gmail.com
Tue Jul 28 20:32:05 UTC 2015
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>
More information about the es-discuss
mailing list