자바스크립트🔥
ES6 / 클래스 / 3편 / 프로토타입 및 정적 메소드를 사용한 this 바인딩
나섬애드
2021. 5. 7. 13:53
시부레 말이 왜케 어려운건지🔥🔥
일단 Class내부에 있는 모든 내용은 Strict 모드로 실행됨.
때문에 Strict 모드에서는 자동으로 바인딩이 안됨.
따라서 Strict 모드에서 사용하는 this는 Undefined 됨.
this는 호출방식에 따라 동적으로 this가 결정됨.
- 함수 호출시 this : window
- 메소드 호출시 this : 메소드 객체
- 내부함수 호출시 this : window
- 엄격모드에서의 this : undefined
- 이벤트 리스너 호출시 this : 이벤트 객체
- 생성자 함수 호출시 this : 생성된 새 객체
- Arrow 함수는 일반적인 this 바인딩과 다르게 Lexical this를 가진다.
- (Arrow 함수 호출시 this : 함수 선언시의 상위 스코프의 this)
위 상황 중 내가 살펴볼 곳은 4번. 엄격모드에서의 this는 undefined.
- strict 모드에서 함수를 실행하면 this들은 undefined가 된다.
- 내부 함수 호출시에도 undefined가 된다.
- 의도치않게 전역객체에 바인딩 된 this를 사용하는 것을 막을 수 있다. ( 이런 경우가 있나? 언제 발생하는거지.. 🙄)
- null 참조로 인해 죽기때문에 의도하지 않은 동작을 하는 것 보다 쉽게 오류검증 가능.
strict 모드에서는 this가 자동으로 바인딩 되지는 않고, this값은 전달된 채로 유지됨.
class Animal {
speak() {
return this;
}
static eat() {
return this;
}
}
let obj = new Animal();
obj.speak(); // the Animal object
let speak = obj.speak;
speak(); // undefined
Animal.eat() // class Animal
let eat = Animal.eat;
eat(); // undefined
위에 작성된 코드를 전통적 방식의 함수기반의 non–strict mode 구문으로 재작성하면, this 메서드 호출은 기본적으로 전역객체인 초기 this 값에 자동으로 바인딩 됩니다. Strict mode에서는 자동 바인딩이 발생하지 않습니다; this 값은 전달된 대로 유지됩니다.
function Animal() { }
Animal.prototype.speak = function() {
return this;
}
Animal.eat = function() {
return this;
}
let obj = new Animal();
let speak = obj.speak;
speak(); // global object (in non–strict mode)
let eat = Animal.eat;
eat(); // global object (in non-strict mode)