본문 바로가기

4. Programming/4.3 JavaScript

11. This

함수가 호출될 때, 매개 변수로 전달되는 인자 값 외에도 argumentsthis 를 암묵적으로 전달받음.


자바스크립트의 this는 함수 호출 방식에 따라 바인딩 되는 객체가 달라짐. 


function func1 () {
console.log(arguments, 'arguments')     //Arguments [callee: ƒ, Symbol(Symbol.iterator): ƒ] "arguments"
console.log(this, 'this') //Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …} "this"
}

func1();

함수 호출과 바인딩

함수 호출에 따라 어떤 객체를 this에 바인딩할지가 결정 됨. 

함수 호출 패턴 (Function Invocation Pattern)

전역 객체(Global Object)는 모든 객체의 유일한 최상위 객체를 의미하며, 일반적으로 Browser-side에서는 window, Server-side에서는 global을 의미.


this === window; //true


전역 객체는 전역 스코프(Global Scope)를 갖는 전역 변수(Global variable)를 프로퍼티로 소유.

글로벌 영역에 선언한 함수는 전역 객체의 프로퍼티로 접근할 수 있는 전역 변수의 메소드.

전역 함수 및 내부 함수의 경우도 this는 전역 객체에 바인딩.


var var1 = 'Global';

console.log(var1); // Global
console.log(window.var1); // Global

function func1() {
console.log('Hello!');
}
window.func1(); //Hello!


메세지 호출 패턴 (Method Invocation Pattern)

함수가 객체에 프로퍼티이면 메소드 호출 패턴으로 호출. 이때 메소드 내부의 this는 해당 메소드를 소유한 객체 즉 해당 메소드를 호출한 객체에 바인딩 됨.

var obj1 = {
content : 'This is obj1',
print : function() {
console.log(this.content);
}
}

obj1.print();


생성자 호출 패턴 (Constructor Invocation Pattern)

기존 함수에 new 연산자를 붙여서 호출하면 해당 함수는 생성자 함수로 동작.

// 생성자 함수
function Car(name) {
this.name = name;
}

var audi = new Car('audi a8');
var volkswagen = new Car('benz c class');


Apply 호출 패턴 (Apply Invocation Pattern)

자바 스크립트 엔진의 암묵적 this 바인딩 이외에 this 바인딩 이외에 this를 특정 객체에 명시적으로 바인딩하는 방법
function Car(name) {
this.name = name;
}

var audi = {};
Car.apply(audi, ['a8']);


참고 : https://poiemaweb.com/

'4. Programming > 4.3 JavaScript' 카테고리의 다른 글

12. 실행 컨텍스트  (0) 2018.10.10
10. Scope Life-Cycle  (0) 2018.08.15
9. 프로토타입과 객체지향  (0) 2018.08.09
8. 타입 체크  (0) 2018.07.24
7. Function (함수)  (0) 2018.07.15