Javascript
this this this this
codevil
2022. 4. 7. 11:21
자바스크립트에서의 this는 무엇을 의미하는 걸까?
1. 전역 this
node.js에서의 this, 브라우저에서의 this는 할 수 있는 것이 다르다. 예를들면 node.js에서의 this는 alert가 안되고, 브라우저에서의 this는 alert가 가능하다. 이렇게 가장 밖에서 쓰는 this를 전역 this라고 한다.
(this.process.env는 node에는 있지만, 브라우저에서는 없다)
2. 함수 this
function(){
console.log(this)
}
함수에서의 this는 window, 전역을 이야기한다
3. 메소드 this
const obj = {
name : 'obj',
method : function(){
return this.name
}
}
같은 depth의 this값을 불러온다
이렇게 사용하는 this는 암시적인 this 바인딩이라고 한다
const person = {
name : '사람',
sayName : function(){
return this.name
}
}
const zero = {
name : '베이스',
sayName : function(){
return this.name
}
}
function sayFullName(firstName){
return firstName + this.sayName()
}
sayFullName.call(person, '장')
sayFullName.call(zero, '장')
다음과 같이 바인딩을 하면, call(부를 오브젝트 , '들어갈 변수') 그리고 앞에 있는 function의 this는, 부를 오브잭트의 this와 같아진다 즉. sayFullName.call(person, '장')을 사용한다면, 우선 fullName인 장 + this.sayName() 그리고 this.sayName()은 person에있는 sayName이 실행되어, 장사람이 된다. 만일 바인딩할때 넣고싶은, 변수가 배열이면 apply를 사용하면 된다. 대신 firstName대신 arguments로 넣어야 한다