this์ ๋ํด์ ๊ณต๋ถ๋ฅผ ํ๋ค๊ฐ this bindingํ๋ ๋ถ๋ถ์ ๋ํด์ ์ง์ ์์ ๋ฅผ ๋ง๋ค์ด ์ดํด๋ฅผ ํด๋ณด๊ณ ์, Array.prototype.map ๋ฉ์๋๋ฅผ ์ง์ ๊ตฌํํด๋ณด์๊ณ , ๊ทธ ๊ณผ์ ์์ this ๋ฐ์ธ๋ฉ์ ์ค์์ฑ์ ๋ฐ๊ฒฌํ์ต๋๋ค.
ํนํ ์ฝ๋ฐฑ ํจ์ ๋ด๋ถ์์์ this๊ฐ ์์๊ณผ ๋ค๋ฅด๊ฒ ๋์ํ๋ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ ๊ณผ์ ์ ๋ค๋ฃน๋๋ค.
// map ๋ฉ์๋ ๊ตฌํ
Array.prototype.map = function () {
var newArr = [];
console.log(this); // [1, 2, 3]
for (var i = 0; i < this.length; i++) {
console.log(this[i]);
newArr.push(this[i]);
}
return newArr;
};
var newArr = [1, 2, 3].map(function(item) {
console.log(this); // [1, 2, 3]
return item * 2;
});
console.log("result: ", newArr); // [1,2,3] - ์์๊ณผ ๋ค๋ฅด๊ฒ [2,4,6]์ด ์๋!
Array.prototype.map = function (callback) {
var newArr = [];
for (var i = 0; i < this.length; i++) {
newArr.push(this[i]); // ์ด๋ผ? callback์ ์ด๋๋ก..?
}
return newArr;
};
Array.prototype.map = function (callback) {
var newArr = [];
for (var i = 0; i < this.length; i++) {
var mappedValue = callback(this[i]); // this๋ ์ด๋๋ก ๊ฐ์๊น..
newArr.push(mappedValue);
}
return newArr;
};
Array.prototype.map = function (callback, thisArg) {
var newArr = [];
for (var i = 0; i < this.length; i++) {
// thisArg๊ฐ ์์ ๊ฒฝ์ฐ this๋ฅผ ์ฌ์ฉํ๊ณ , call๋ก this๋ฅผ ๋ช
์์ ๋ฐ์ธ๋ฉ!
var mappedValue = callback.call(thisArg || this, this[i]);
newArr.push(mappedValue);
}
return newArr;
};
callback.call(thisArg || this, this[i])
thisArg์ ์ญํ