JS this

최정환·2021년 6월 25일
0

JS 문법 따로따로 

목록 보기
1/4

this


1. 자바스크립트는 기본적으로 전역 객체에 컨텍스트가 바인딩되는 규칙을 가진다.

2. ES6부터 사용할수 있는 화살표 함수(arrow function)는 기존의 컨택스트 바인딩 규칙을 따르지 않는다. 기존 컨택스트는 실행 시점에 바인딩 규칙이 적용된다. "동적 바인딩"이라 할수 있다.

3. this는 현재 실행되는 코드의 실행 컨텍스트


📋 개체 메서드에서 메서드의 소유자를 참조함.

단독으로 사용시 소유자는 전역 개체이므로 전역 개체를 참조함.


coworkers.showAll = function() {
  for (var key in coworkers) {
    document.write(key + ' : ' + coworkers[key] + '<br>');
  }
}

coworkers라는 변수 이름이 바뀌면 함수를 수정해야 하기 때문에 위와 같은 방법은 좋지 않다.
coworkers.showAll = function() {
  for (var key in this) {
    document.write(key + ' : ' + this[key] + '<br>');
  }
}

coworkers대신에 메소드가 쓰인 객체를 가리키는 this를 사용한다.


📋 Dot Notation (도트 표기법)

person의 key와 value를 부여한 후 .로 값에 접근하는 방식
도트 앞에 있는 객체 자체(person)를 가르킴.

person 개체는 fullName 메서드의 소유자


let id = 9484;
let firstName = "Chris";

const person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};
person.fullName();	// John Doe

🧹 예시 하나 더

let number = 55;
foo = () => {	
  	let number = 77;
 	bar(number)
}
bar = () => {
	console.log(this.number);
}
foo();	// 55

bar 함수 내에 this.number는 전역 변수인 number = 55 를 사용하고 있기 때문에 foo안에 있는 bar에는 전역변수가 들어간다.


📋 브라우저 창에서 전역 개체는 object Window.

let x = this;
// x = window

📋 call(), apply()

this의 값을 한 문맥에서 다른 문맥으로 넘기기 위해 사용한다.

🧹 예시 1

// call 또는 apply의 첫 번째 인자로 객체가 전달될 수 있으며 this가 그 객체에 묶임
var obj = {a: 'Custom'};

// 변수를 선언하고 변수에 프로퍼티로 전역 window를 할당
var a = 'Global';

function whatsThis() {
  return this.a;  // 함수 호출 방식에 따라 값이 달라짐
}

whatsThis();          // this는 'Global'. 함수 내에서 설정되지 않았으므로 global/window 객체로 초기값을 설정한다.
whatsThis.call(obj);  // this는 'Custom'. 함수 내에서 obj로 설정한다.
whatsThis.apply(obj); // this는 'Custom'. 함수 내에서 obj로 설정한다.

🧹 예시 2

function add(c, d) {
  return this.a + this.b + c + d;
}

var o = {a: 1, b: 3};

// 첫 번째 인자는 'this'로 사용할 객체이고 (var o로 부터 가져오는),
// 이어지는 인자들은 함수 호출에서 인수로 전달된다.
add.call(o, 5, 7); // 16

// 첫 번째 인자는 'this'로 사용할 객체이고 (var o로 부터 가져오는),
// 두 번째 인자는 함수 호출에서 인수로 사용될 멤버들이 위치한 배열이다.
add.apply(o, [10, 20]); // 34

📋 new를 사용한 함수

new를 사용해 생성자 함수로 만들어 사용시 this는 빈 객체가 된다.

function Person () {
console.log(this);
}

new Person();

이때 this는 빈 객체를 가리키며 생성자 함수는 this라는 빈 객체를 return함.

function Person () {
console.log(this.age);	// undefined
  this.age = 100;
console.log(this.age);	// 100
}

new Person();

person 함수가 new와 함께 생성자 함수로 사용되는 즉시 함수 내부 this는 빈 객체가 되며

this.age = 100;

을 통해 그 빈 객체에 age라는 속성을 추가하고 값 100을 할당하게 된다.
그리고 person 함수는 age:100 이라는 객체를 return한다.

class Car {
  constructor(a, b) {
    this.name = a;
    this.price = b;
  }
}

const myCar = new Car("장난감", 1000);



참고 :
https://www.boostcourse.org/cs124/lecture/194641?isDesc=false
https://www.w3schools.com/js/js_this.asp
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/this
https://im-developer.tistory.com/96

0개의 댓글