this

맨땅헤딩! ㅣ 2022. 12. 10. 11:09

이번 주제는 자바스크립트에서 this에 관한 주제이다.

 

전역 객체 😊

전역 객체 (global Object)
모든 객체의 최상위 객체
자바스크립트에서는 window 객체

 

전역 객체에 바인딩 되는 경우
this는 전역 객체(window)에 바인딩
1. 전역 함수
2. 내부 함수
3. 콜백 함수 등등..

 

예시 👇🏻👇🏻

 function sFoo() {
 	console.log("sFoo ::: " + this); //sFoo ::: [object Window]
 }

 

this 😊

함수 호출 방법에 따라 값이 결정 => 바인딩

기본적으로는 브라우저에서는 window를 가리킴


this 호출방법 😊

  • 함수에서 this

예시 👇🏻👇🏻

function foo() {
        this.b = 30;
        console.log(this.b);
      }

      foo(); //30
      console.log(this.b); //foo()없으면 undefined, 있으면 30

 

  • 메서드에서 this
  • -> 해당 메서드를 호출한 객체로 바인딩

예시 👇🏻👇🏻

var person = {
    firstName: "Heading",
    lastName: "Man",
    fullName: function () {
        return this.firstName + " " + this.lastName;
    },
};

console.log(person.fullName()); //"Heading Man"

 

  • 생성자 안에서 this
  • -> 생성자 함수가 생성하는 객체로 바인딩

예시 👇🏻👇🏻

function Person(name) {
    this.name = name;
}

var kim = new Person("kim");
var lee = new Person("lee");

console.log(kim.name); //kim
console.log(lee.name); //lee

 

  • apply,call,bind 에서 this
  • -> call, apply는 첫번째 인자로 this 대체값을 받고 parameter를 받음
  • -> apply는 array형태로 전달 받음

예시 👇🏻👇🏻

const obj = { name: "kim" };

const say = function introduce(city) {
    console.log(`hello, my name is ${this.name}, I live in ${city}`);
};

say("incheon");
say.call(obj, "incheon");
say.apply(obj, ["incheon"]);

const func = say.bind(obj);
func("incheon");

 

  • 화살표 함수에서 this
  • -> 화살표 함수는 this가 존재하지 않기 때문에 그 상위 this를 참조
  • -> 메소드 안에서는 화살표 함수 사용 X
  • -> 생성자 함수에서 화살표 함수 사용 X

예시 👇🏻👇🏻

window.x= 10;
const normal = function () {
    return this.x;
};

const arrow = () => this.x;

console.log(normal.call({ x: 30 })); // 30
console.log(arrow.call({ x: 30 })); // 10

 

마무리 😊

이번 주제 함수 선언식과 표현식에 관하여 알아보았다.

'JavaScript > JavaScript 공부' 카테고리의 다른 글

렉시컬 스코프  (0) 2022.12.18
함수 선언식, 함수 표현식 차이  (0) 2022.12.04
Array 메서드  (0) 2022.11.27
Hoisting  (0) 2022.11.20