NOTION 정리/Javascript

this

dev_sr 2023. 11. 3. 17:36

자바스크립트의 this는 함수를 호출하는 방식에 따라 동적으로 결정됨(누가 불렀냐에 따라 결정)

 

*바인딩 : this가 호출 방식에 따라서 특정 '객체'에 연결되는 것

 

 

1. 일반 함수 내부에서는 this는 글로벌 객체와 바인딩 됨

function foo() {
	return this;
}

console.log(foo()) //window

 

 

2. 객체 메서드 내부에서는 호출한 객체와 바인딩

const animal = {
	name: “dog”,
	getName: function() {
		console.log(this); 
	}
}
animal.getName(); //animal(dog) 객체


const animal2 = {
  name: “cat”,
  getName: animal.getName
}
animal2.getName(); //animal2(cat) 객체

const animal3 = animal.getName;
animal3(); //window객체(밖에서 부른 것 중 최상단 객체)

 

 

3. 생성자 함수 내부는 인스턴스

function dog(){
    this.name = "해피",
    this.log = function(){
        console.log(this.name);
    }    
}

let dog1 = new dog();
console.log(dog1) //dog {name: '해피', log: ƒ}
console.log(dog1.log()) //해피

 

 

4. bind, call, apply

 

bind

첫번째 인자에 this를 바인딩하지만 함수를 실행하지 않고 새로운 함수를 반환한다.

첫번째 인자 이후 값은 함수의 인자로 전달

const animal = {
	name: “dog”,
	getName: function() {
		console.log(this); 
	}
}
animal.getName(); //animal(dog) 객체


const animal2 = {
  name: “cat”,
  getName: animal.getName
}

const bindName = animal2.getName.bind(animal);
bindName(); //animal(dog)출력

 

function log(nation, pet){
    console.log(this.name);
    console.log(this.age);
    console.log(nation);
    console.log(pet);
}

const person = {
    name: 'kim',
    age: 30
}

const bindFunction = log.bind(person, "korea", "puppy");
bindFunction(); //실행이 필요함
//kim
//30
//korea
//puppy

 

 

call

함수를 실행하고 함수의 첫번째 인자에 this를 바인딩, 나머지는 함수에 인자로 전달

function log(nation, pet){
    console.log(this.name);
    console.log(this.age);
    console.log(nation);
    console.log(pet);
}

const person = {
    name: 'kim',
    age: 30
}

log.call(person, "korea", "puppy");
//kim
//30
//korea
//puppy

 

 

apply

call 이랑 비슷하지만 인자를 배열로 전달

function log(nation, pet){
    console.log(this.name);
    console.log(this.age);
    console.log(nation);
    console.log(pet);
}

const person = {
    name: 'kim',
    age: 30
}

log.apply(person, ["korea", "puppy"]);
//kim
//30
//korea
//puppy

 

 

5. DOM 요소는 DOM 요소랑 바인딩

document.body.onclick=function(){
    console.log(this);  //body   

    function inner(){
        console.log('inner',this);
    }

    const arrowInner = () => console.log('arrowInner',this);

    inner();   // window  
    arrowInner();  //body
};

 

 

6. DOM 요소 선택 시 화살표 함수 => 외부 함수 컨텍스트 이용

document.body.onclick = () =>{
    console.log(this); //window   

    function inner(){
        console.log('inner',this);
    }

    const arrowInner = () => console.log('arrowInner',this);

    inner(); //window     
    arrowInner(); //window
};

 

 

7. 객체에서 화살표 함수 => 외부 함수 컨텍스트 이용

const animal = {
	name: "dog",
	getName: function() {
		console.log(this); 
	},
        getNameArrow: () => {console.log(this)}
}
animal.getName(); // animal 객체
animal.getNameArrow(); // window

 

 

8. 객체에서 중첩함수일때 일반 함수와 화살표 함수 차이

const animal = {
	name: "dog",
	getName: function() {
		console.log(this); 
                function inner(){console.log("inner", this);}
                inner();
	},
}
animal.getName();
//animal 객체
//"inner" window

const animal = {
	name: "dog",
	getName: function() {
		console.log(this); 
                let arrow = () => console.log("arrow", this);
                arrow();
	},
}
animal.getName();
//animal 객체
//"arrow" animal 객체

 

 

참고

https://velog.io/@realryankim/JavaScript-this%EB%9E%80

 

[JavaScript] this란?

JavaScript 'this'

velog.io

https://ko.javascript.info/object-methods