관리 메뉴

진취적 삶

22 this 본문

개발 도서/자바스크립트 deepdive

22 this

hp0724 2023. 7. 12. 11:39

22.1 this 키워드

객체 = 상태(프로퍼티) + 동작 (메서드 )

메서드가 자신이 속한 객체의 프로퍼티를 참조하려면 자신이 속한 객체를 가리키는 식별자를 참조해야한다.

this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조변수 이다 .

this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할수 있다.

js this 는 함수가 호출되는 방식에 따라 this에 바인딩될 값, 즉 this 바인딩이 동적으로 결정된다.

console.log(this); //window
function square(number) {
  console.log(this); //window
  return number * number;
}

square(2);

const person = {
  name: "l",
  getName() {
    console.log(this); // name :l ,getName
    return this.name;
  },
};
console.log(person.getName()); //l

function Person() {
  this.name = this.name;
  console.log(this); //person name :l
}
const me = new Person("lee");

22.2 함수 호출방식과 this 바인딩

this 바인딩은 함수 호출 방식 , 함수가 어떻게 호출되었는지에 따라 동적으로 결정

22.2.1 일반함수호출

function foo () {
	console.log("foo's this " ,this) //window
	function bar() {
		console.log("bar's this " ,this)  //window 
} 
bar()
}

메서드 내에 중접된 함수도 this 바인딩은 전역 객체가 바인딩 된다.

일반함수로 호출된 모든 함수(중첩함수 ,콜백 함수 ) 내부의 this에는 전역 객체가 바인딩된다.

22.2.2 메서드 호출

this에 바인딩될 객체는 호출 시점에 결정된다.

function Person(name) {
  this.name = name;
}
Person.prototype.getName = function () {
  return this.name;
};

const me = new Person("lee");

console.log(me.getName()); //lee

Person.prototype.name = "haha";

console.log(Person.prototype.getName()); //haha

22.2.3 생성자 함수 호출

생성자 함수는 객체를 생성하는 함수

일반 함수는 new 연산자와 함께 호출되면 생성자 함수로 동작한다.

new 연산자가 없으면 일반함수로 동작

22.2.4

function getThisBinding() {
  return this;
}

const thisArg = { a: 1 };

console.log(getThisBinding());

//getThisBinding 함수를 호출하면서 인수로 전달한 객체를 getThisBinding 함수의 this 바인딩
console.log(getThisBinding.apply(thisArg));
console.log(getThisBinding.call(thisArg));

apply 와 call 메서드를 본질적인 기능은 함수를 호출하는것이다 .

apply 와 call 메서드는 호출할 함수에 인수를 전달하는 방식만 다를뿐 this 와 동일

function getThisBinding() {
  return this;
}

const thisArg = { a: 1 };

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

bind 메서드는 메서드의 this 와 메서드 내부의 중첩 함수 또는 콜백 함수의 this 불일치 문제를 해결하기 위해 유용히 사용

const person = {
  name: "suha",
  foo(callback) {
    //여기서 this는 person 객체 가르킴
    console.log(this); //메서드 내의 this { name: 'suha', foo: [Function: foo] }
		//bind 매서드로 callback 함수 내부의 this 바인딩을 전달 
		//this에 바인딩될 객체는 호출 시점에 결정된다. 
    setTimeout(callback.bind(this), 100);
  },
};

person.foo(function () {
  console.log(`hi my name is ${this.name}`); // undefined
  //일반 함수로 호출된 콜백 함수 내부의 this.name은 window.name 전역 객체를 가리킨다.
  //person.foo 내부에서 this.name 은 window .name 과 같아진다.
  //person.foo 내부의 this 와 콜백 함수의 this 가 달라지는 상황이 된다.
  // 따라서 undefined 가 된다 .
});

'개발 도서 > 자바스크립트 deepdive' 카테고리의 다른 글

30 Date  (0) 2023.07.12
21 빌트인 객체  (0) 2023.07.12
23 실행 컨텍스트  (0) 2023.07.12
24 클로저  (0) 2023.07.12
25 클래스  (0) 2023.07.12