본문 바로가기
FrontEnd/Java Script

this

by Fathory 2020. 12. 31.

this : 메서드 내부에서 객체에 접근할 수 있는 지시자? 예약어?

 

 

let company = {
	name: "nhn",
    where: "pangyo",
    
    companyName() {
    	alert(this.name); // this 는 현재 메소드의 객체인 company를 나타낸다.
    }
};
company.companyName();

 

동일한 코드는 다음과 같이 작성할 수 있다. 

let company = {
	name: "nhn",
  where: "pangyo",
    
    companyName() {
    	alert(company.name);
    	return company.name; // this. 대신 user 사용
    }
};
company.companyName();

다만 후자의 경우, 원하지 않는 형태의 동작을 할 수도 있다.

 

예를 들어서, company 객체를 다른 객체로 덮어쓰게 된다면 원하지 않는 동작을 하게 된다.

 

let company = {
	name: "nhn",
	where: "pangyo",
    
    companyName() {
    	alert(this.name);
    	return this.name;
    }
};


let nhn = company;
company = null;

nhn.companyName();

 

company 객체에서 접근자를 this로 작성하면 에러가 발생하지 않는다.

null로 변경된 객체가 아닌, 할당한 객체가 그대로 사용되기 때문이다.

 

자바스크립트에서는 모든 함수에 this를 사용할 수 있다.

this의 값은 런타임에 결정된다.

 

function test(){
 	// 엄격모드에서는 undefined, 아닌 경우에는 전역객체를 참조, 브라우저에서는 window 객체를 참조하게된다.
	alert(this);
}

test(); // 에러가 발생하지 않는다.

동일한 함수라도 다른 객체에서 호출했다면 'this’가 참조하는 값이 달라진다.

let nhn = { name: "NHN" };
let naver = { name: "NAVER" };

function companyName() {
	alert(this.name);
}

// this는 . 앞의 객체를 참조한다. 따라서 동일한 메소드를 호출하더라고 this가 가리키는 객체가 달라진다.
nhn.func = companyName;
naver.func = companyName;

nhn.func();
naver.func();

 

화살표함수는 고유한 this가 없다.

화살표 함수가 아닌 외부의 함수에서 this를 가져온다.

 

let company = {
  name: "nhn",
  companyName() {
    let getCompanyName = () => alert(this.name);
    getCompanyName();
  }
};

company.companyName(); // "nhn"

 

* 추가

체이닝을 사용하려면, 객체 내에 선언한 메소드에 대해서 this를 리턴하면 된다.

 

객체 리터럴에서 this를 사용하면 에러가 발생한다.

function createCompany() {
  return {
    name: "REVAN",
    ref: this
  };
};

let company = createCompany();

alert( company.ref.name ); // Error: Cannot read property 'name' of undefined

createCompany 함수는 객체를 반환한다.

this의 값은 호출 시점에 정의된다.

 

createCompany에서 this는 전역객체가 된다.

메서드가 아니라 함수로 호출되었기 때문이다.

this는 전역객체가 되고, 코드블럭과 객체 리터럴은 여기에 영향을 주지 않는다.

 

전역객체가 아닌 선언한 함수의 객체를 지정하려면 다음과 같이 작성한다.

 

function createCompany() {
  return {
    name: "REVAN",
    ref() {
    	return this;
    }
  };
}

let company = createCompany();

alert( company.ref().name ); // ref()에서 this가 지정하는 객체는 객체리터럴(return 하는 객체)가 된다.

 

예제) 계산기

 

let calculator = {
  a:0,
  b:0,
  read() {
    this.a = +prompt("첫번째 숫자를 입력하세요", 0); 
    this.b = +prompt("첫번째 숫자를 입력하세요", 0);
  },
  sum() {
    return this.a + this.b;
  },
  mul() {
    return this.a * this.b;
  }
  
  // 각 메소드에서 this가 가리키는 객체는 calculator객체
};

calculator.read();
alert( calculator.sum() );
alert( calculator.mul() );

 

반응형