javascript (this)

CHAN YE·2022년 10월 14일
0

1. 단독으로 쓴 this = window

ex.) var x= this; //window

'use strict';

var x = this;
console.log(x); //Window

엄격모드에서도 마찬가지

2. 함수 안에서 쓴 this = window

var num = 0;
function addNum() {
  this.num = 100;
  num++;
  console.log(num); // 101
  console.log(window.num); // 101
  console.log(num === window.num); // true
}
addNum(); 

3. strict mode(엄격 모드)에서는 함수 내의 this에 디폴트 바인딩이 없기 때문에 undefined가 됩니다.

function myFunction() {
  return this;
}
console.log(myFunction()); //undefined  

따라서 this.num을 호출하면 undefined.num을
호출하는 것과 마찬가지기 때문에 에러가 납니다.

4. 이벤트 핸들러 안에서 쓴 this


var btn = document.querySelector('#btn')
btn.addEventListener('click', function () {
  console.log(this); //#btn
}); 

이벤트 핸들러에서 this는 이벤트를 받는 HTML 요소를 가리킵니다.

5. 생성자 안에서 쓴 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

하지만 new 키워드를 빼먹는 순간 일반 함수 호출과 같아지기 때문에, 이 경우는 this가 window에 바인딩됩니다.

var name = 'window';
function Person(name) {
  this.name = name;
}
 
var kim = Person('kim');
 
console.log(window.name); //kim

6. 명시적 바인딩을 한 this

function whoisThis() {
  console.log(this);
}
 
whoisThis(); //window
 
var obj = {
  x: 123,
};
 
whoisThis.call(obj); //{x:123}

call과 apply 둘다 첫번째 인자로 this로 사용할 객체를 보내고 두번째 인자로 apply는 배열을 보내는 반면 call은 인자 하나 하나씩 보낸다.

---------------- apply ----------------
function Character(name, level) {
  this.name = name;
  this.level = level;
}
 
function Player(name, level, job) {
  Character.apply(this, [name, level]);
  this.job = job;
}
 
var me = new Player('Nana', 10, 'Magician');
console.log(me);
//Player {name: 'Nana', level: 10, job: 'Magician'}
----------------- call -----------------
function Character(name, level) {
  this.name = name;
  this.level = level;
}
 
function Player(name, level, job) {
  Character.call(this, name, level);
  this.job = job;
}
 
var me = new Player('Nana', 10, 'Magician');
  console.log(me);
  //Player {name: 'Nana', level: 10, job: 'Magician'}
---------- call 객체정의하여 사용하기 ----------
function Character(name, level) {
  this.name = name;
  this.level = level;
}
 
function Player(name, level, job) {
  Character.call(this, name, level);
  this.job = job;
}
 
var me = {};
Player.call(me, 'nana', 10, 'Magician');
console.log(me);
//me {name: 'Nana', level: 10, job: 'Magician'}

7. 객체(유사배열)에 배열메소드사용

var args =Array.prototype.slice.apply(arguments);
var args2 =Array.prototype.push.call(list, 'Choi');
var children = document.body.children; // HTMLCollection
Array.from(children).forEach(function (el) {
  el.classList.add('on'); 
});

8. 화살표 함수에서 this

  • 함수(new를 붙였을시 객체)안에서의 함수 즉 내부함수 에서는 this가 전역객체가 된다.
var Person = function (name, age) {
  this.name = name;
  this.age = age;
  this.say = function () {
    console.log(this); // Person {name: "Nana", age: 28}
 
    setTimeout(function () {
      console.log(this); // Window
      console.log(this.name + ' is ' + this.age + ' years old');
    }, 100);
  };
};
var me = new Person('Nana', 28);
 
me.say(); //global is undefined years old

setTimeout안에있는 함수에서는 this로 Person을 가져오지 못하고 window를 가져오게 된다. 이러한 현상을 막기위해 arrow function을 사용하면 원하는 this값을 가져올 수 있게된다.

var Person = function (name, age) {
  this.name = name;
  this.age = age;
  this.say = function () {
    console.log(this); // Person {name: "Nana", age: 28}
 
    setTimeout(() => {
      console.log(this); // Person {name: "Nana", age: 28}
      console.log(this.name + ' is ' + this.age + ' years old'); 
    }, 100);
  };
};
var me = new Person('Nana', 28); //Nana is 28 years old
profile
php웹개발자

0개의 댓글