JS-this
| topics | 200-프론트개발 |
| types | 이론 학습 |
| tags | #javascript #this #binding |
js) 22장 this
this
- 자신이 속한 객체 또는 생성할 인스턴트를 가리키는 자기 참조 변수.
- 호출될 때 동적으로 값이 결정된다.
생성자 함수
생성자 함수에서는 this 가 추후 생성될 인스턴스에 바인딩됨.
function Circle(radius){
this.radius = radius;
this.getDiameter = function (){
return 2 * this.radius;
}
}
const circle1 = new Circle(10);
const circle2 = Circle(10)
console.log(circle1.getDiameter()); //20
console.log(circle2) //undefined
console.log(circle2.getDiameter()); //error
“new” 와 함깨 호출하지 않으면 일반함수로 동작.
메서드
메서드 내부의 this는 메서드를 호출한 객체에 바인딩된다.
const person = {
name:'Lee',
getName(){
console.log(this);
return this.name;
}
}
function Person(name){
this.name = name;
this.getName = function(){
console.log(this);
return this.name;
}
}
const person1=new Person("Lee");
const getName1 = person.getName;
person.getName();//{ name: 'Lee', getName: [Function: getName] }
person1.getName();//Person { name: 'Lee', getName: [Function] }
getName1();//window
//return는 undefined window.name이없으니깐..
일반함수
일반 함수로 호출된 모든 함수의 내부 this에는 전역 객체가 바인딩된다.
function foo(){
console.log(this);//window
function bar(){
console.log(this);//window
}
bar();
}
const obj = {
value: 100,
foo(){
console.log(this);//obj
function bar(){
console.log(this);//window
}
bar();
},
poo(){
setTimeout(function(){
console.log(this);//window
},100)
},
}
이런 중첩 함수나 콜백함수에 this를 일치시키기 위한 방법
변수에 할당
const obj = {
value: 100,
poo(){
const that = this;
setTimeout(function(){
console.log(this);//window
console.log(that.value);//100
},100)
},
}
화살표함수
화살표 함수의 내부 this는 상위 스코프 this를 가리킨다.
const obj = {
value: 100,
poo(){
const that = this;
setTimeout(()=>{
console.log(this.value);//100
},100)
},
}
Function.prototype.apply/call/bind 이용
- apply, call
기본적으론 함수 호출하는 것.
첫번째 인수로 전달한 객체를 this에 바인딩
function getThisBinding(){
console.log(arguments);
return this;
}
const thisArg = { a : 1 };
console.log(getThisBinding.apply(thisArg,[1,2,3]));
//Arguments(3) 1,2,3
//{a : 1}
console.log(getThisBinding.call(thisArg,1,2,3));
//Arguments(3) 1,2,3
//{a : 1}
- bind
함수 호출 X , this 바인딩이 bind의 첫번째 인수로 교채된 함수로 반환.
function getThisBinding(){
console.log(arguments);
return this;
}
const thisArg = { a : 1 };
console.log(getThisBinding.bind(thisArg)());
//{a : 1}
var healthObj = {
name : "달리기",
lastTime : "PM10:12",
showHealth : function() {
setTimeout(function(){
console.log(this.name + "님, 오늘은 " + this.lastTime + "에 운동을 하셨네요");
}.bind(this), 500);
}
}