console.log(this) //{window}
function 함수(){
console.log(this); //undefined
}
👉 결과
⭐ this를 출력하면 window가 나오는 이유 ..?
<script>
window :{
함수(){
console.log(this)
}
}
</script>
var obj = {
data : {
func : function(){
//함수를 가지고 있는 오브젝트
console.log(this)//data{}
},
func2 : () => {
//Arrow Function 특징 : this값을 함수밖에 있던거 그대로 씀
console.log(this) //window{}
}
},
func : function(){
// this = 나를 포함하고 있는 오브젝트
console.log(this); //obj{}
}
}
obj.data.func();
obj.data.func2();
obj.func();
👉 결과
function machine(){ //오브젝트 생성기계(constructor)
this.name = 'kim' //새로생성되는 오브젝트(instance)
}
var obj = new machine();
document.getElementById('button').addEventListener('click',function(e){
//지금 이벤트 동작하는곳
console.log(this); //button 출력
console.log(e.currentTarget); //button 출력
var arr = [1,2,3];
arr.forEach(function(a){
//콜백함수 => 함수 안에 들어가는 함수를 콜백함수
//Case study) 콜백함수(일반함수)이기 때문에 window출력
console.log(this)
})
})
👉 결과
var object = {
names : ['김', '이', ' 박'],
func : function() {
console.log(this); // 위 함수를 소유한 object
object.names.forEach(function(){
//콜백함수(일반함수)이므로 window
console.log(this)//window
})
//Case Study) arrow function안에서의 this?
object.names.forEach(() => {
//내부의 this값을 변화시키지 않음(외부 this값 그대로 재사용)
console.log(this)//위 함수를 소유한 object
})
}
}
object.func();
👉 결과