[JS] 함수 호출과 this

Im-possible·2025년 4월 23일

함수 호출

함수로 호출

- 함수명()
- this는 window 객체로, window 객체는 어디서나 참조 가능하므로 this를 사용할 필요 없음
function f1(){
  console.log(this); // window 객체 출력
  this.console.log('hello'); // this가 window 객체이기 때문에 hello 출력
  window.console.log('hi'); // hi 출력
  console.log('window 생략'); // window 생략 출략
};
const f2 = function(){
  console.log(this); // window 객체 출력
};

// 함수로 호출
f1();
f2();

console.log(this); // window 객체 출력

메서드로 호출

- 객체에 정의된 메서드를 호출할 때
- 객체.메서드명()
- this는 메서드를 정의한 객체
- 함수를 하나만 정의하고 여러 객체에서 메서드로 사용
const getPingName = function(){
  return this.name;
}

const baro = new Object();
baro.name = '바로핑';
baro.age = 9;
baro.getName = getPingName;

const rara = {
  name: '라라핑',
  age: 8,
  getName: getPingName
};

// 메서드로 호출
console.log(baro.age, baro.getName()); // getName()의 this는 baro, 9 바로핑 호출
console.log(rara.age, rara.getName()); // getName()의 this는 rara, 8 라라핑 호출

화살표 함수 호출

- 일반 함수나 메서드와 동일하게 호출하지만 함수 내부에 arguments나 this가 생성되지 않고 상위 컨텍스트의 arguments, this 사용
const getPingName = () => {
  return this.name; // 상위 Scope this를 찾는다 (window)
}

const baro = new Object();
baro.name = '바로핑';
baro.age = 9;
baro.getName = getPingName;

const rara = {
  name: '라라핑',
  age: 8,
  getName: getPingName
};

console.log(baro.age, baro.getName()); // getName()의 this는 global, 9 undefined 출력
console.log(rara.age, rara.getName()); // getName()의 this는 global, 8 undefined 출력
// 전역변수로 name이 선언되어있지 않기 때문에 undefined 출력 

apply(), call() 메서드로 호출

- 함수에 정의된 메서드
- 함수명.apply() , 함수명.call()
- this는 apply(), call() 메서드의 첫번째 인자로 전달되는 객체
- this를 명시적으로 지정할 수 있음
- 콜백 함수 호출 시 주로 사용
function add(a, b){
  console.log(this);
  const result = a + b;
  return result;
}

console.log(add.apply({name: '어플'}, [50, 60])); // 110, this = {name: '어플'}
console.log(add.call({name: '콜'}, 30, 40)); // 70, this = {name: '콜'}

apply(p1, p2)

- 두개의 매개변수를 가짐
- 첫 번째 매개변수(p1): this로 사용할 객체 전달
- 두 번째 매개변수(p2): 함수에 전달할 인자값 배열

call(p1, p2, p3, ...)

- 여러개의 매개변수를 가짐
- 첫 번째 매개변수(p1): this로 사용할 객체 전달
- 두 번째 이후의 매개변수(p2, p2, p3, ...): 함수에 전달할 인자값을 차례대로 지정

배열의 push 메서드를 이용하여 객체를 배열처럼 동작시키기

- this로 지정된 Array 객체의 length 속성값에 해당하는 속성을 만들고 지정한 요소를 저장한 후 length를 하나 증가시킨다
- Array.prototype.push.call(객체, 추가할 요소)
const arr = { 
  length: 3,
  0: 'orange',
  1: 'yellow',
  2: 'green',
  push: function(elem){
    Array.prototype.push.call(this, elem);
  }
};

arr.push('black')
arr.push('white');

배열 데이터를 각각의 매개변수로 분리하여 전달

function smallest(nums){
  const min = Math.min.apply(...nums) // 전개 구문
  return min;
}

console.log(smallest([10,100]));  // 10
console.log(smallest([200,100,50,60,80,30]));  //30
console.log(smallest([100,20,60,50,70]));  // 20

생성자 함수

- new 함수명(), 함수명은 대문자로 시작
- this는 생성자를 통해 생성된 객체
- 생성자로 호출된 함수는 비어있는 객체를 새로 생성
- 새로 생성된 객체는 this 매개변수로 생성자 함수에 전달
- 명시적으로 반환하는 객체가 없다면 생성된 객체를 반환
function Ping(name, age){
  this.age = age;
  this.name = name;
  this.getName = function(){
  return this.name 
  };
}

const baro = new Ping('바로핑', 9); 
const rara = new Ping('라라핑', 8);
const copyPing = new Ping('카피핑', 12);

baro.age++;
baro.height = 120;

console.log(baro.age, baro.getName()); 
console.log(rara.age, rara.getName()); 
console.log(copyPing.age, copyPing.getName());

0개의 댓글