카테고리 없음

[JS] 함수, this 이해하기

dotudy 2025. 7. 1. 23:22

자바스크립트에서 함수를 선언하는 방법에는 몇 가지가 있다.

 

1. 

기본적인 함수 정의에 대해서 알아보자.

function greet(name){
    console.log("hello " + name);
}
greet("alberto"); //hello alberto

원시 자료형이 함수에 전달될 때는 참조가 아니라 값의 형태로 전달된다. 따라서 변경 사항이 전역적으로 반영되지 않는다. 

반면, 객체나 배열을 함수에 전달할 때는 참조로 전달된다. 따라서 이는 해당 값에 대한 수정 사항이 원래의 객체에 반영됨을 의미한다. 예를 들어 보자.

let myInt = 1;

function increase(value){
    return value += 1;
}

console.log(myInt); //1
console.log(increase(myInt)); //2
console.log(myInt); //1

함수를 통해 myInt의 값을 증가시키고 난 후에도 myInt 원본의 값에는 변함이 없음을 확인할 수 있다.

 

let car = {
    color: 'red',
    wheels: 4
};

function coloring(objcar){
    objcar.color = 'blue';
    return objcar;
}

console.log(car); //{ color: 'red', wheels: 4 }
console.log(coloring(car)); //{ color: 'blue', wheels: 4 }
console.log(car); //{ color: 'blue', wheels: 4 }

반면, 매개면수 objcar은 car의 참조이므로 color의 값을 수정하면 car 객체도 변경됨을 확인할 수 있다.

 

2.

함수 표현식을 사용하는 방법이다.

const greeter = function greet(name){
    console.log("hello " + name);
};

greeter("woni");

 

greeter라는 const에 greet라는 함수를 할당했다. 이를 사용하여 익명 함수를 만들 수도 있다.

 

3.

익명 함수를 사용하는 방법이다.

const greeter = function(name){
    console.log("hello " + name);
};

greeter("woni");

모두 동일하게 hello woni를 출력한다.

 

4. 

화살표 함수를 사용할 수도 있다.

const greeter = (name) => {
    console.log("hello " + name);
};

greeter("woni");

function도 사라지고 매개변수만 남긴 채 뒤에 화살표(=>)가 있는 것을 확인할 수 있다.

 

함수 스코프 이해하기

1. 전역 스코프

  이를 가지는 변수를 코드의 어느 곳에서나 접근할 수 있다.

2. 블록 스코프

  이를 가지는 변수는 변수가 선언된 블록 내부에서만 접근할 수 있다.

  여기서 블록은 함수, 루프, {}로 구분되는 모든 영역을 말한다.

 

var myInt = 1;

if (myInt == 1){
    var secondInt = 2;
    console.log(secondInt); //2
}

console.log(secondInt); //2

secondInt는 if 내에 선언해서 블록 스코프를 가진다고 생각할 수 있다.

하지만 var 키워드로 선언된 변수는 해당 경우에서는 블록 스코프를 가지지 않기 때문에 외부 블록에서도 이를 접근할 수 있다. 따라서 오류가 나지 않고 그대로 2가 출력된다.

(var에 대한 자세한 스코프는 다음 글에 정리할 예정이다.)

 

var myInt = 1;

if (myInt == 1){
    let secondInt = 2;
    console.log(secondInt); //2
}

console.log(secondInt); //ReferenceError: secondInt is not defined

하지만 위와 같은 경우는 다르다.

let과 const 키워드로 선언된 변수는 변수가 선언된 위치에 해당하는 블록 스코프를 가지게 된다. 

 

this 키워드 이해하기

const car = {
    color: 'red',
    wheels: 4,
    logColor: function (){
        console.log(this.color);
    }
};

car.logColor(); //red

this의 값은 함수가 호출되는 방식에 따라 다르다. 위의 예에서 함수는 객체의 메서드로 호출되었다. 

 

function logThis(){
    console.log(this);
}

logThis(); //<ref *1> Object [global] {~

위의 함수는 전역 범위에서 호출했으므로 this 값은 global을 참조함을 알 수 있다.

strict mode로 설정하면 실수로 global을 참조하는 것을 방지할 수 있다. 자바스크립트 파일의 시작 부분에 'use strict';를 삽입하면 된다.

'use strict';

function logThis(){
    console.log(this);
}

logThis(); //undefined

 

this의 값을 수동으로 설정하고 싶을 때는 .bind()를 사용하면 된다.

const car = {
    color: 'red',
    wheels: 4,
    logColor: function (){
        console.log(this.color);
    }
};

const getcolor = car.logColor;
console.log(getcolor()); //undefined
//전역 범위의 this가 호출되기 때문에 그 값은 global 객체가 되고 이 객체이는 color가 없으므로 undefined가 된다.
//.bind()를 사용해서 getcolor의 this 키워드가 괄호 안의 객체, car를 참조함을 알린다.

const boundgetcolor = getcolor.bind(car);
console.log(boundgetcolor()); //red

const boundget = car.logColor.bind(car);
console.log(boundget()); //red