console.log(this); // {window}

function thiss() {
console.log(this); // {window}
}
thiss();

: 모든 전역변수, 함수, DOM을 보관하고 관리하는 전역객체
document.getElementById(), alert(), console.log() 등을 보관하는 큰 오브젝트
<script>
let x = 300;
</script>
이렇게 변수나 함수를 만들면 window라는 큰 오브젝트 공간에 자동으로 생성됨
: 'use strict'라는 키워드를 페이지 최상단에 추가하면 strict mode로 자바스크립트를 작성 가능
undefined라는 값으로 강제로 지정<script>
'use strict';
function aaa(){
console.log(this) // strict mode일 때 함수 안에서 쓰면 this는 undefined
}
aaa();
</script>
: object 자료형 내에 함수들이 있을 수 있는데 거기서 this값은 나를 포함하고 있는 오브젝트를 뜻함
let obj = {
data : 'kim',
hello : function(){
console.log('안녕');
}
}
obj.hello(); // 안녕 출력
let obj2 = {
data : 'kim',
this2 : function(){
console.log(this); // 나를 포함하고 있는 오브젝트
}
}
obj2.this2();

let obj3 = {
data : {
name : 'park',
this3 : function(){
console.log(this);
}
}
}
obj3.data.this3();

JavaScript에서 비슷한 object를 여러 개 만들고 싶을 때,
오브젝트를 복사하는 것이 아니라 constructor를 만들어서 사용함
constructor는 오브젝트를 복사해서 생성해 줌
함수 문법을 만든 후에 안에 this.___ 를 추가하면 여기부터 나오는 this는
새로 생성될 오브젝트를 의미
function con(){
this.name = 'kim';
}
function con(){
this.name = 'kim'
}
let obj = new con();
/*
new 키워드를 이용하면 새로운 오브젝트를 꺼낼 수 있고
새로운 오브젝트는 this 키워드 덕분에 {name:'kim'} 이라는 값을 가지고 있음
*/
eventlistener 안에서 쓰면 this는 e.currentTarget이라는 의미document.getElementById('btn').addEventListener('click', function(e){
console.log(this) // e,currentTarget과 같은 의미
});
그냥 있는 콜백함수는 일반함수와 같기 때문에 window 출력
document.getElementById('btn').addEventListenr('click', function(e){
let arr = [1, 2, 3];
arr.forEach(function(){
console.log(this); // window
})
})
let obj = {
names : ['kim', 'lee', 'park'];
func : function(){
obj.names.forEach(funciton(){
console.log(this)
})
}
}
forEach() 안에 있는 함수에 this가 들어 있지만 특별한 역할을 하는 함수가 아닌 일반함수이면 window 출력
let obj3 = {
names : ['kim', 'lee', 'hong'],
fucn : function(){
console.log(this);
obj2.names.forEach(()=>{ // arrow function : 내부 this 값 변화시키지 않음
console.log(this); // 상위 코드에 있는 this 즉. object
})
}
}
function은
1. 여러가지 기능을 하는 코드를 한 단어로 묶고 재사용 할때
2. 입출력 기능 만들때 사용함
arrow function은 함수 본연의 입출력기능을 직관적으로 잘 표현
예시 1) 일반함수
var obj1 = {
fu : function(){ console.log(this) }
}
obj1.fu(1) // 1 출력
예시 2) arrow 함수
var obj2 = {
fu : () => { console.log(this) }
}
obj2.fu(1) // window