화살표함수 this 예제

this binding?

by youknowimean

HTML

<button id="btn">
 Press
</button>

JavaScript

var obj = {
    names: ["seo"],
    text: "님 안녕하세요",
    print: function() {
        console.log(this.text)
        this.names.forEach(name => {
            console.log(this)   // seo님 안녕하세요
        })
    }
}
obj.print()

/*
var obj = {
    names: ["seo"],
    text: "님 안녕하세요",
    print: () => { console.log(this.text) } // undefined
}
obj.print() */

// 일반 함수 사용
const btn = document.getElementById('btn');

var myObj = {
	count: 0,
	setCounter: function() {
		console.log(this.count);
		btn.addEventListener('click', (function() {
			console.log(this);
		}).bind(this));
	}
};

myObj.setCounter();