./dev |
Original theme by orderedlist (CC-BY-SA)
Where applicable, all content is licensed under a CC-BY-SA.
|
Consider the following:
let f = [], i=0;
while (i<2) {
.push( function() { return i; } );
f++;
i
}for (let j=0; j<f.length; j++) {
console.log(f[j]());
}
This will result in:
2
2
To fix:
let f = [], i=0;
while (i<2) {
.push( (function(t) { return function() { return t; }; } )(i) );
f++;
i
}for (let j=0; j<f.length; j++) {
console.log(f[j]());
}
Note:
The following will work “as expected”:
let f = [];
for (let i=0; i<2; i++) {
.push( function() { return i; } );
f
}for (let j=0; j<f.length; j++) {
console.log(f[j]());
}
Which prints:
0
1
An article talks about how this is effectively equivalent to:
let f = [];
let i=0;
for (i=0; i<2; i++) {
let _i = i;
.push( function() { return _i; } );
f
}...
And is due to what is, in my opinion, a dirty hack in the ECMAScript standard to scope variable inside the for
declaration into the for
body.
function foo(x) {
this.x = x;
this.s = 'foo';
}
.prototype.F = function() { console.log(this.x, this.s); }
foo.prototype.G = function(x) { this.x = x; }
foo
let bar = new foo(1);
.F()
bar.G(2);
bar.F(); bar
Results in:
1 foo
2 foo
(SO)
It gets pretty complicated.
function *h1(x) {
console.log("h1.0:x", x);
yield 9;
++;
xconsole.log("h1.1:x", x);
yield 10;
++;
xconsole.log("h1.2:x", x);
yield 11;
++;
xconsole.log("h1.3:x", x);
return -2;
}
function *h0(x) {
let v = yield* h1(x);
console.log("h0>", v);
return -1;
}
function _h(x) {
let hgen = h0(x);
let hv = {};
for (hv = hgen.next(); !hv.done; hv = hgen.next()) {
console.log("_h>", hv);
}
console.log("fin>", hv);
}
_h(127);
h1.0:x 127
_h> { value: 9, done: false }
h1.1:x 128
_h> { value: 10, done: false }
h1.2:x 129
_h> { value: 11, done: false }
h1.3:x 130
h0> -2
fin> { value: -1, done: true }