본문 바로가기
Today I Learned

Scope 와 관련 용어 정리

by rinny01 2025. 1. 15.
반응형

this : 

어떤 특정 객체를 가리키고 있는 값

함수가 어떻게 호출되었느냐에 따라 동적으로 가리키는 객체가 결정된다.

 

this 바인딩 : 

함수마다 this라는 특별한 객체가 있꼬 함수 호출이 되었을때 this값이 결정되는데, this값이 결정되는것을 의미함

  • 기본 바인딩 : 일반 함수 호출에서 this는 전역 객체를 가리킨다 (window)

 

  • 암묵적 바인딩 : 객체의 메소드 호출에서 this는 해당 객체를 가리킨다.
const person = {
  name: 'Alice',
  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
};
person.greet();

const obj1 = {
  name: 'obj1',
  sayName() {
    console.log(this.name); //this : obj1
  },
};

const obj2 = {
  name: 'obj2',
  sayName: obj1.sayName, // 괄호없잖아. 호출 안된거임. (그냥 할당)
  
  //sayName : (){obj1.sayName();} : obj1로 간다. 실행의 주체따라가기.
}

obj2.sayName();//obj2를 가리킨다.

 

  • 명시적 바인딩 : call, apply / bind 메소드를 이용해 능동적으로 바인딩 하는것. 즉 개발자가 직접 명시하는것.
    • call, apply : 함수를 호출하는 방식 (매개변수가 필요하다) - 즉시 실행
    • bind 
function sayName() {
  console.log(this.name);
}

function callCB(cb) {
  cb();
}

const obj = {
  name: '홍길동',
};

callCB(sayName.bind(obj));//이런식으로 바로 bind해준다

 

  • 화살표 함수에서의 this
    • 이친구는 ES6에서 나왔다. 아~무 거도 따르지 않고 자기 마음대로 호출시 바로 window를 가르키는것을 명심하자

 

 

프로토타입 : 

객체들이 공통으로 사용할수 있는 속성이나 메서드를 정의한 공간

 

Scope : 

사전적 의미 : 범위

자바스크립트에서 : 변수와 함수가 유효한 범위를 뜻함.

1. 함수 scope (var)

  • var x 변수는 foo()함수 안에서만 적용 된다.
  • if문은 함수가 아니기 때문에 var secret는 전역 스코프에서 사용 가능하다. (안전하지 않다)
function foo() {
  var x = 'local';
  console.log(x); // 출력: local
}

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

if(5 > 4) {
	var secret = '12345';
} // 얘는 함수가 아니네? 그럼 나는 위로 올라가야지~
secret // '12345'

 

2. 블록 scope (let, const)

  • {} 로 감싸진 코드 내에서만 변수가 유효하다.
{
  let y = 'block scoped';
  console.log(y); // block scoped
}

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

 

 

스코프 체인 :

  • 변수를 찾을떄 현재 스코프에서 찾고, 없으면 상위 스코프에서 찾는다.
  • console.log(a) : 변수 a를 찾는다 > 없다 > 상위 스코프에서 찾는다 > 없다 > 전역에서 찾는다 > 'global'이다. > 출력
  • 즉, 가장 가까운 접근 가능한 변수를 찾는다.
let a = 'global';
function outer() {
  let b = 'outer';
  /* if (true) {let d = 10;} */

  function inner() {
    let c = 'inner';
    console.log(a); // 출력: global
    console.log(b); // 출력: outer
    console.log(c); // 출력: inner
    // console.log("d:",d);
  }
  inner();
}
outer();

 

렉시컬 스코프

  • 자바스크립트는 함수가 선언된 시점에서 상위 스코프를 결정하는 렉시컬 스코프를 따릅니다.
  • first(); > second()함수 찾아가기 > console.log(y) > y 찾기 > 없음 > 상위함수가 없으니까 전역에서 찾기 > y=5 > 5출력 
  • second() > 위와 같은 방식
// 아래 코드의 출력 결과는?
const y = 5;

function first() {
  const y = 20;
  second();
}

function second() {
  console.log(y);
}

first(); // 5
second(); // 5

 

 

class : 

  • 객체지향 프로그래밍의 중요한 개념으로, 객체를 생성하기 위한 템플릿 역할을 해준다.
  • 객체의 생성, 수정을 클래스 안에서 해준다.
class Car {
  constructor(brand, model) { //생성자함수 'new'키워드와 함께 사용한다
    this.brand = brand;
    this.model = model;
  }

  displayInfo() {
    console.log(`${this.brand} ${this.model}`); 
  }
}

//인스턴스 생성
const car1 = new Car('toyota','corolla')

 

  • 인스턴스 메소드 (동적 메소드)
  • 정적 메소드 (static)
class User {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    // 동적 메소드 - 인스턴스에 의존
    getUserInfo() {
        return `${this.name} is ${this.age} years old.`;
    }

    // 정적 메소드 - 인스턴스와 무관하게 동작
    static compareAges(user1, user2) {
        return user1.age - user2.age;
    }
}

// 인스턴스 생성
const user1 = new User('Alice', 25);
const user2 = new User('Bob', 30);

// 동적 메소드 호출
console.log(user1.getUserInfo());

// 정적 메소드 호출 (인스턴스 생성 없이 호출)
console.log(User.compareAges(user1, user2));

 

 

반응형
LIST