this 4가지동작 (+ call,apply,bind)

0

javascript

목록 보기
24/34
post-thumbnail

this는 함수 실행시 호출 방법에 의해 결정되는 특별한 객체 입니다.

지금부터 this의 4가지 동작 방식에 대해 살펴 보도록 합시다

1. 기본바인딩(전역객체)

this를 콘솔에서 console.log(this) 를 치면
이런식으로 보입니다.

javascript 실행 환경의 전역 객체 입니다.
this의 첫번째 동작 방식은, this가 전역 객체를 context객체로 갖는것 입니다.

  • 브라우저 환경에서 this는 기본적으로 window 객체를 가리킵니다
  • node.js 환경에서 this는 기본적으로 module.exports 객체를 가리킵니다

2. 암시적 바인딩

어떤 객체를 통해 함수가 호출되다면 그 객체가 바로 this의 context 객체가 됩니다.

var b =100;

function test(){
  console.log(this.b);
}

var obj = {
  a : 20,
  func1 : test,
  func2 : function() {
    console.log(this.b);
  }
};

obj.func1(); //undefined
obj.func2(); //undefined

var gFunc1 = obj.func1; //gFunc1 = test = console.log(this.b); = var b = 100; 
gFunc1(); //100

this를 그냥 사용하면 암시적으로 전역 객체에 바인딩이 되는 것 입니다.


3. 명시적 바인딩

함수 call,apply, bind 메소드를 가지고 있다.
세가지 메소드는 첫번째 인자로 넘겨주는 것이 this 입니다.
이를 명시적 바인딩이라 합니다.

📌 call

const mike = {
	name : 'mike'
}

const tom = {
  name : 'tom'
}

function showthisName(){
  console.log(this.name);
}

function update(birthYear, occupation){
  this.birthYear = birthYear;
  this.occupation = occupation;
}

update.call(mike, 1999,'singer'); //{name : 'mike', birthYear : 1999, occupation : 'singer'}

call메소드를 사용할때 첫번째 매개변수로 들어온 mike는 this를 뜻 한다.
1999는 birthYear의 값 / 'singer'은 occupation 의 값이다.

📌 Apply

const mike = {
	name : 'mike'
}

const tom = {
  name : 'tom'
}

function showthisName(){
  console.log(this.name);
}

function update(birthYear, occupation){
  this.birthYear = birthYear;
  this.occupation = occupation;
}

update.apply(mike,[1999,'singer']); //{name : 'mike', birthYear : 1999, occupation : 'singer'}

call과 동일한데 매개변수 형태가 []로 들어간다는것이 다르다
배열요소를 함수 매개변수로 이용해야 할 때 apply를 이용한다. !!

🌸 call과 apply의 차이

const nums = [1,2,3,4,5];
const min = Math.min(nums); // NaN
const min = Math.min(...nums) // 1
const min = Math.min.apply(null,nums) // 1
const min = Math.min.call(null,...nums) //1

Math.min 메소드는 ()괄호 안에 배열이 아닌 숫자들의 집합이 와야 합니다.
nums는 배열이므로 NaN이 출력되고
배열 형태의 nums를 숫자의 집합으로 나타내기 위해 ...을 함므로써 Math.min(...nums)은 1이 출력 되었다.
apply는 배열의 형태도 숫자의 집합으로 바꿔주므로 nums로 매개변수이용이 가능하다.
그러나 call은 매개변수 그대로 이용하므로 ...을 붙여 숫자의 집합으로 바꿔준다.
apply와call의 null은 딱히 가르키는 this가 없을때 null을 쓴다.

📌 bind

const mike = {
	name : 'mike'
}

function update(birthYear, occupation){
  this.birthYear = birthYear;
  this.occupation = occupation;
}

const updateMike = update.bind(mike);

updateMike(1980,'police');//{name : 'mike', birthyear : 1980, occupation : 'police'}

bind의 매개변수 mike가 this이다.
함수의 this값을 영원히 바꿀수 있다.

🌸 bind,call,apply차이

const user = {
  name : 'mike',
  showName : function(){
    console.log(`hello, ${this.name}`);
  }
}
user.showName(); // hello,mike
let fn = user.showName;
fn.call(user);	//hello,mike
fn.apply(user);	//hello,mike
let boundFn = fn.bind(user);
boundFn(); //hello,mike

4. new바인딩

생성자 호출은 객체.메소드() 과 같이 객체 내에 메소드를 호출 하는 방법과 비슷하지만, 객체가 new 키워드를 이용해서 만들어졌다는 것이 다릅니다. 이 때의 객체는 우리가 인스턴스라고 부릅니다. 즉 인스턴스.메소드()의 형태의 호출입니다.

function Car(name, brand, color) {
     this.name = name;
     this.brand = brand;
     this.color = color;
     this_value_in_constructor = this;
    }
const mycar = new Car('mini', 'bmw', 'red')
console.log(mycar.name); //'mini'
console.log(mycar.brand); //'bmw'
console.log(mycar.color); //'red'
profile
👩🏻‍💻항상발전하자 🔥

0개의 댓글