this
아무것도 없는 상태에서 this는 글로벌객체인 window를 가르킨다.
자바스크립트 this가 결정되는 시점은
선언시점이 아닌 누가 실행하는지에 따라서 결정된다.
consoleA를 실행할때 testObj가 실행하고 있으므로
this는 testObj를 가르킨다.
const testObj = {
a: '1234',
consoleA: function() {
console.log(this.a);
}
}
testObj.consoleA(); //1234
변수에 메소드를 할당해서 실행하는경우
실행할 때 this는 testObj가 아닌 window를 가르킨다.
const testObj = {
a: '1234',
consoleA: function() {
console.log(this.a);
}
}
const test = testObj.consoleA;
test(); //undefinded
할당해서 실행하는경우 this가 실종되는 이슈 해결법
this를 고정해주는 방법으로 call, apply, bind를 사용할 수 있다.
call, apply
call, apply는 첫번째 인자로 지정할 bind를 넣어주고, 두번째 인자로 함수에 필요한 파라미터를 넣어준다.
const testobj = {
name: 'aa'
};
function sayTest(city) {
console.log(`${city}에 사는 ${this.name}`)
};
sayTest.call(testobj, 'seoul'); // seoul에 사는 aa
여기서 call, apply의 차이점은 apply는 두번째 인자로 배열을 받는 것 이다.
const testobj = {
name: 'bb'
};
function sayTest(city) {
console.log(`${city}에 사는 ${this.name}`)
};
sayTest.apply(testobj, ['youngin']); //youngin에 사는 bb
bind
call, apply와 동일하게 this를 지정하는 메소드이다.
다른점은 함수를 바로 실행하지 않는다는 점이다.
const testobj = {
name: 'bb'
};
function sayTest(city, age) {
console.log(`${city}에 사는 ${this.name}은 ${age}세 입니다.`)
};
const testSayObj = sayTest.bind(testobj, 'youngin', '13');
testSayObj(); // youngin에 사는 bb은 13세 입니다.
화살표함수에서는 call, apply, bind메소드를 이용해 this를 바인드 할 수 없다.
'NOTE' 카테고리의 다른 글
node.js, npm, npx (0) | 2023.04.19 |
---|---|
함수와 메소드 차이 (0) | 2023.04.19 |
한글, 영문 폰트 다르게 적용하기 (0) | 2023.04.17 |
자바스크립트 sort()로직 (0) | 2023.04.15 |
매개변수, 인자, 인수 (0) | 2023.04.05 |