-
this의 개념Javascript 2020. 8. 9. 12:32
1. 함수실행에서의 this
함수실행에서
함수자체가 아닌this는 전역객체* 실행문맥: 함수가 작성 됐을 때가 아닌 실행될 당시의 문맥.
function sum(a, b) { console.log(this === window); // => true this.myNumber = 20; return a + b; } // 함수 문맥으로 실행된 sum() // this in sum() is a global object (window) sum(15, 16); // => 31 window.myNumber; // => 20
sum() 호출시 자바스크립트는 자동으로 this에 전역객체를 세팅.
웹 브라우저에서의 전역객체는 window이므로 this가 window객체를 가리키는 것은 실행문맥이라는 전제.2. 메소드 실행
메소드는 객체 내부 속성으로 정의된다.
var myObject = { // helloFunction is a method helloFunction: function() { return 'Hello World!'; } }; var message = myObject.helloFunction();
helloFunction은 myObject 내부의 속성.
myObject.helloFunction()은 속성접근자를 통한 메소드 호출.메소드 실행에서의 this는 메소드를 소유하고 있는 객체를 가리킨다.
var myObject = { myMethod: function() { this; } }; myObject.myMethod(); // this == myObject
var calc = { num: 0, increment: function() { console.log(this === calc); // => true this.num += 1; return this.num; } }; // method invocation. this is calc calc.increment(); // => 1 calc.increment(); // => 2
3. Arrow function
arrow function에서 this는 arrow function이 정의된 곳의 문맥을 따른다.
자신을 둘러싼 환경에서 this가 가지는 문맥은 arrow function에서도 그대로 적용된다.
이렇듯 arrow function에서의 this는 한번 bound되면 절대 바뀌지 않는 렉시컬 문맥을 따른다.
(this의 참조값이 결정되면 실행문맥이 달라져도 변하지 않음 == Lexical this)
this는 실행문맥에 따라 계속해서 다른 값을 참조.
function objFunction() { console.log('Inside `objFunction`:', this.foo); // 13 return { foo: 25, bar: function() { console.log('Inside `bar`:', this.foo); // 25 }, }; } // objFunction의 `this`를 오버라이딩한다. objFunction.call({foo: 13}).bar();
arrow function은 실행문맥에 따라 변경되지 않음
function objFunction() { console.log('Inside `objFunction`:', this.foo); // 13 return { foo: 25, bar: () => console.log('Inside `bar`:', this.foo) // 13 }; } objFunction.call({foo: 13}).bar();
this
- this는 현재 context(맥락)이다.
- this가 불린 영역의 전역객체를 의미한다.
function test() { console.log(this); //window } ex) var obj = { func: function() { if( o === this ) { console.log("o === this"); // o === this } } }
Prototype
- 객체 안의 프로퍼티
- 상속할 때 사용
function test() { } console.log(test.prototype); // {} test.prototype.name="dylee"; console.log(test.prototype); // {name: "dylee"};
function Person(name) { this.name = name; } Person.prototype.name = null; Person.prototype.introduce = function() { return 'My name is ' + this.name; } function Programmer(name) { this.name = name; } Programmer.prototype = new Person(); // Person 객체 상속 var p1 = new Programmer('egoing'); console.log(p1.introduce());
참고
'Javascript' 카테고리의 다른 글
데이터타입과 연산자 (0) 2020.08.17 변수의 유효범위 개념 (0) 2020.08.09 ==와 ===의 차이점 (0) 2020.08.09