This 알아보기

Jeon seong jin·2020년 6월 21일
0

This

this 는 현재 실행 문맥이다. 2. this는 현재 실행되는 코드의 실행 컨텍스트를 가리키는것

  • 자바스크립트에서 this는 실행 컨텍스트가 생성될 때 함께 결정된다. 실행 컨텍스트는 함수를 호출할 때 생성되므로 this는 호출할 때 결정된다.

  • 실행문맥 : '호출자'가 누구냐는 것

2. 기본적으로 this는 전역객체를 가리킨다.

  • 전역공간에서의 this는 전역 객체를 가리킨다. 전역 컨텍스트를 생성하는게 전역 객체이기 때문에
console.log(this === wondow); // true

var a = 1;
console.log(a); //1
console.log(window.a); //1
console.log(this.a); //1

"전역변수"를 선언하면 자바스크립트 엔진은 이를 전역객체의 프로퍼티로 할당한다.

console.log(this === window) // true, 호출자는 window

const caller = {
  f : function () {
    console.log(this === window)
  }.
}
caller.f() //false, 호출자는  caller 객체

첫번째는 윈도우 객체의 메소드 호출, 두번째는 함수 내부의 메소드 호출이라 생각하자.
(첫번째는 함수 호출, 두번째는 메소드 호출이라 하면 더 혼란 스럽다.)

생성자 함수와 객체에서의 쓰임새

생성자는 new로 객체를 만들어 사용하는 방식

function NewObject(name, color) {
  (this.name = name),
    (this.color = color),
    (this.isWindow = function() {
      return this === window;
    });
}

const newObj = new NewObject('nana', 'yellow');
console.log(newObj.name); //nana
console.log(newObj.color); //yellow
console.log(newObj.isWondow()); //false

new키워드로 새로운 객체를 생성하면 생성자 함수내에 "this"는 new 를 통해 만들어진 새로운 변수가 됩니다.
일반적인 객체에서는 "this"는 어떻게 동작할까?

const human = {
  name: 'j',
  age: 20,
  getName: function() {
    return this.name;
  }
};
cosnole.log(human.getName()); // "j"

const otherHuman = human;

otherHuman.name = 'c';
console.log(human.getName()); //'c'
console.log(otherHuman.getName()); //'c'

일반 객체도 생성자 함수와 크게 다르지 않다. 주목할 점은 otherHuman에서 변경한 name의 값이 human.getName()으로 호출해도 동일하게 변경이 되어있다. 이유는 otherHuman은 human의 참조 변수이므로 변경하게 되면 같이 변경이 된다. 이를 피하기 위해서는 Object.assign()메서드를 이용하여 별도의 객체로 만들자!

const person = {
  name: 'j',
  age: 20,
  getName() {
    return this.name;
  }
};

console.log(person.getName());
const person2 = Object.assign({}, person);

person2.name = 'c';
console.log('person:', person.getName()); //j
console.log('person2:', person2.getName()); //c
profile
-기록일지

0개의 댓글