// AS-IS
var oldBinding = {
name : 'old name',
arr : ['oldArr1', 'oldArr2'],
printArr: function() {
var that = this; // oldBinding 을 가리키는 this 를 that 에 할당
this.arr.forEach(function (v) {
console.log(that.name, v);
});
}
};
oldBinding.printArr(); // old name oldArr1, old name oldArr2
// TO-BE
const newBinding = {
name : 'new name',
arr : ['newArr1', 'newArr2'],
printArr() {
this.arr.forEach(v => { // 화살표 함수를 사용했기 때문에 상위 스코프의 this 를 그대로 사용
console.log(this.name, v);
});
}
};
newBinding.printArr(); // new name newArr1, new name newArr2
Ly8gQVMtSVMKdmFyIG9sZEJpbmRpbmcgPSB7CgluYW1lIDogJ29sZCBuYW1lJywKCWFyciA6IFsnb2xkQXJyMScsICdvbGRBcnIyJ10sCglwcmludEFycjogZnVuY3Rpb24oKSB7CgkJdmFyIHRoYXQgPSB0aGlzOwkJLy8gb2xkQmluZGluZyDsnYQg6rCA66as7YKk64qUIHRoaXMg66W8IHRoYXQg7JeQIO2VoOuLuQoJCXRoaXMuYXJyLmZvckVhY2goZnVuY3Rpb24gKHYpIHsKCQkJY29uc29sZS5sb2codGhhdC5uYW1lLCB2KTsKCQl9KTsKCX0KfTsKb2xkQmluZGluZy5wcmludEFycigpOwkvLyBvbGQgbmFtZSBvbGRBcnIxLCBvbGQgbmFtZSBvbGRBcnIyCgoKLy8gVE8tQkUKY29uc3QgbmV3QmluZGluZyA9IHsKCW5hbWUgOiAnbmV3IG5hbWUnLAoJYXJyIDogWyduZXdBcnIxJywgJ25ld0FycjInXSwKCXByaW50QXJyKCkgewoJCXRoaXMuYXJyLmZvckVhY2godiA9PiB7CQkvLyDtmZTsgrTtkZwg7ZWo7IiY66W8IOyCrOyaqe2WiOq4sCDrlYzrrLjsl5Ag7IOB7JyEIOyKpOy9lO2UhOydmCB0aGlzIOulvCDqt7jrjIDroZwg7IKs7JqpCgkJCWNvbnNvbGUubG9nKHRoaXMubmFtZSwgdik7CgkJfSk7Cgl9Cn07Cm5ld0JpbmRpbmcucHJpbnRBcnIoKTsJCS8vIG5ldyBuYW1lIG5ld0FycjEsIG5ldyBuYW1lIG5ld0FycjI=