Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

22장 this, 23장 실행 컨텍스트 #16

Merged
merged 2 commits into from
Jan 20, 2025
Merged

22장 this, 23장 실행 컨텍스트 #16

merged 2 commits into from
Jan 20, 2025

Conversation

Turtle-Hwan
Copy link
Member

@Turtle-Hwan Turtle-Hwan commented Jan 18, 2025

늦어서 죄송합니다
양이 상당하네요

Copy link
Collaborator

@whddltjdwhd whddltjdwhd left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

챕터 양이 상당이 많네요. . . 정리하느라 고생하셨습니다..!

console.log(x); // 1
```

- var 변수는 오로지 함수와 코드 블록만 지역 스코프로 인정하는 함수 레벨 스코프를 따른다.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

그럼 다음과 같이 let을 var로 변경했을 때는 별도의 렉시컬 환경이 생기지 않는 걸까요??

var x = 1;

if (true) {
  var x = 10; // -> 렉시컬 환경이 새로 생기나?
  console.log(x); // 10
}

console.log(x); // 1

x = 1;
```

- 위와 같은 소스코드가 실행될 때, 먼저 소스 코드 평가 과정에서 변수 선언문 `var x;`를 먼저 실행한다.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let 또는 const 의 경우엔 아예 초기화 자체가 되질 않아서 접근할 수 없죠!

그리고 함수 표현식으로 선언한 함수의 경우엔, 해당 함수가 평가될 때 함수의 이름과 똑같은 이름의 식별자를 객체 환경 레코드에 바인딩된 BindingObject를 통해 전역 객체에 키로 등록하고 생성된 함수 객체를 즉시 할당한다! 라고 하네요

-> 그럼 전역 렉시컬 환경이 아닌, 함수 또는 블록 렉시컬 환경에서는 전역 객체의 키로 등록하는 과정만 빠지는걸로 이해하면 될까요?

console.log(getThisBinding.bind(thisArg)()); // {a: 1}
```

- bind 메서드는 내부 중첩 함수, 콜백 함수의 this 불일치 문제를 해결할 수 있다.
Copy link
Member

@clicelee clicelee Jan 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이게 2.2 에서 메서드가 다른 변수에 할당된 후 호출되면 일반 함수처럼 동작하여 this가 전역 객체를 가리키기 때문에 나온 해결책이군요

Copy link
Member

@clicelee clicelee left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

고생하셨습니다! 감기 조심하세요~

Comment on lines +132 to +134
- apply와 call 메서드는 함수를 호출하면서 첫 번째 인수로 전달한 특정 객체를 호출한 함수의 this에 바인딩한다.
- apply와 call 메서드는 인수 전달 방식만 다를 뿐 동일하게 동작한다.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

apply와 call에서 함수를 실행할 때 호출 시 첫 번째 인수로 전달된 객체를 this로 바인딩합니다.
명시적 바인딩을 해줘도 bind가 아닌 call, apply의 경우에는 콜백함수가 실행되는 시점에 글로벌 컨텍스트로 바인드됩니다
하지만 호출 후 반환된 값은 함수 실행의 결과이고, this는 다시 호출 컨텍스트에 따라 변경될 수 있습니다.

call, apply는 명시적으로 실행한 결과값을 반환하고 bind는 this를 묶은 함수를 리턴해준다.
apply, call은 함수를 호출한 결과를 반환하고 기존 함수는 this가 다시 끊깁니다

반면 bind로 반환한 함수가 호출될 때 this가 묶인 함수이므로 제대로 된 결과값을 반환합니다

const obj = {
  value: 42,
  hello: function () {
    setTimeout(function () {
      console.log(this.value); // 42
    }.bind(this), 100); // bind로 고정된 this를 가진 새 함수를 반환
  },
};

obj.hello();
const obj = {
  value: 42,
  hello: function () {
    setTimeout(function () {
      console.log(this.value);
    }.call(this), 100); // 여기서 this는 명시적으로 전달되지만, 함수 실행 후 사라짐
  },
};

obj.hello(); // undefined

제가 생각하는게 맞겠죠~~? 다른분들 생각도 궁금합니다

@clicelee clicelee requested a review from songeunseo January 19, 2025 09:12
@Turtle-Hwan
Copy link
Member Author

const person = {
	name: 'Lee',
	foo(callback) {
		setTimeout(callback, 100);
	}
};

person.foo(function() {
	console.log(`Hi! my name is ${this.name}.`);
})

const person2 = {
    name: "123",
	bar() {
		console.log(`Hi! my name is barbar ${this}.`);
	}
}

person.foo(person2.bar);

이 예제에서 person2.bar로 호출했을 때 this가 전역 객체인 window가 되는 이유가 무엇일까요~~?

@MinboyKim @junepil 학생! 숙제입니다!!

Comment on lines +143 to +150
console.log(getThisBinding.apply(thisArg, [1, 2, 3]));

console.log(getThisBinding.call(thisArg, 1, 2, 3));
```

- apply 메서드는 인수를 배열로 묶어 전달하고, call 메서드는 인수를 쉼표로 구분한 리스트로 전달한다.

- apply, call 메서드의 대표적 용도는 arguments 객체와 같은 유사 배열 객체에 배열 메서드를 사용하는 경우이다.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

스터디 중 나온 질문: apply 와 call은 매개변수의 차이 같은데 왜 두개가 존재할까요?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

그냥 진짜 매개변수의 차이인듯...
call apply 공개 영상

@whddltjdwhd
Copy link
Collaborator

10분 테코톡 - JS 실행 컨텍스트 이 영상에서 개념적으로 조금 쉽게 잘 설명해주고 있어요!

@clicelee clicelee merged commit 277b90b into main Jan 20, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants