<script>
console.log(this); // window
function checkThis() {
console.log(this); // window
}
</script>
use strict
mode - function안에서 this<script>
'use strict';
function checkThis(){
console.log(this)
}
checkThis(); // undefined
</script>
use strict
모드의 함수에서 this 기본값은 undefined<script>
var someObject = {
age : 31,
checkThis : function(){
console.log(this);
}
}
someObject.checkThis() // { age : 31, checkThis : f };
</script>
이때 this는 자신을 호출한 바로 상위의 오브젝트를 가리킨다.(최상단의 오브젝트가 아님)
<script>
var someObject = {
age: 31,
data : {
name : "NOHSANGWOO",
checkThis : function(){
console.log(this);
},
},
}
someObject.data.checkThis(); // {name: "NOHSANGWOO", checkThis: ƒ}
</script>
이때 this는 바로 상위의 오브젝트가 someObject.data를 가리키니 해당 값만 출력한다.
<script>
// (1)
function someFunc(){
console.log(this)
}
// (2)
window.someFunc = function(){ console.log(this) };
</script>
1번과 2번의 함수 추가방식은 정확하게 동일한 의미이다.
<script>
function someObj() {
this.firstName = 'NOH';
}
const obj1 = new someObj();
const obj2 = new someObj();
console.log(obj1); // {firstName: "NOH"}
console.log(obj2); // {firstName: "NOH"}
</script>
<script>
document.querySelector('#someButton').addEventListener('click', function(e){
console.log(this); // e.currentTarget과 같은 값
});
</script>
<script>
document.querySelector('someButton').addEventListener('click', function(e){
var arr = [1,2,3];
arr.forEach(function(){
console.log(this); // window
});
});
</script>
<script>
var someObj = {
firstNames : ['NOH', 'KIM'],
checkFunc : function(){
someObj.firstNames.forEach(function(){
console.log(this); // window
});
}
}
</script>
8번과 9번의 예처럼 this는 function을 만날때마다 의미가 바뀔수도 있음
<script>
var someObj = {
firstNames : ['NOH', 'KIM', 'OH'],
// 이때는 this가 함수를 만나서 이 오브젝트를 가리킴
checkFunc : function(){
// this를 물려받은상태
// 이부분에서 arrowfunction적용
someObj.firstNames.forEach(() => {
console.log(this); // {firstNames: Array(3), checkFunc : f }
});
}
}
</script>
<script>
var someObj = {
firstNames : ['NOH', 'KIM', 'OH'],
// 근데 여기도 arrowfunction을 적용한다면? 이때는 this의 기준이 window인상태
checkFunc : () => {
// 이부분에서 arrowfunction적용
someObj.firstNames.forEach(() => {
console.log(this); // window
});
}
}
</script>
arrow function을 사용하면 function을 만나도 this의 의미가 변하지 않는다.
but 물려받은 상위의 this를 기준으로 변하지 않는다는거임
그지같은거 걍 안씀