Created
November 29, 2023 23:08
-
-
Save dfkaye/4adaccc69d417f56c8bd5a8e701288c0 to your computer and use it in GitHub Desktop.
value of `this` inside of array methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 5 September 2023 | |
// `this` inside array methods | |
// Value of `this` inside array depends on whether `this` appears in function | |
// vs. constructor scope, and whether the iteration method calls a normal vs. an | |
// arrow function. | |
/* | |
scope | iterator | |
------------+------------ | |
function | function | |
constructor | function | |
function | arrow | |
constructor | arrow | |
*/ | |
/* test it out */ | |
~(function () { | |
// "use strict"; | |
function X(...a) { | |
var t = this; | |
a.slice().forEach(function (v, i, a) { | |
console.info(t === self ? 'function' : 'constructor', "|", "function"); | |
console.log(v); | |
console.log(this.constructor.name, t.constructor.name); | |
}); | |
}; | |
function Y(...a) { | |
var t = this; | |
a.slice().forEach((v, i, a) => { | |
console.info(t === self ? 'function' : 'constructor', "|", "arrow"); | |
console.log(v); | |
console.log(this.constructor.name, t.constructor.name); | |
}); | |
}; | |
X(1); | |
// function | function | |
// 1 | |
// Window Window | |
new X(2); | |
// constructor | function | |
// 2 | |
// Window X | |
Y(4); | |
// function | arrow | |
// 4 | |
// Window Window | |
new Y(8); | |
// constructor | arrow | |
// 8 | |
// Y Y | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment