함수와 일급 객체

Andy·2023년 8월 30일
0

자바스크립트

목록 보기
22/39

일급 객체

다음과 같은 조건을 만족하는 객체를 일급 객체라 한다.
1. 무명의 리터럴로 생성할 수 있다. 즉, 런타임에 생성이 가능하다
2. 변수나 자료구조(객체, 배열 등)에 저장할수 있다.
3. 함수의 매개변수에 전달할 수 있다.
4. 함수의 반환값으로 사용할 수 있다.

//1. 함수는 무명의 리터럴로 생성할 수 있다.
//2. 함수는 변수에 저장할 수 있다.
//런타임(할당 단계)에 함수 리터럴이 평가되어 함수 객체가 생성되고 변수에 할당된다.
const increase = function(num){
  return ++num;
};

const decrease = function(num){
  return --num;
};

//2. 함수는 객체에 저장할 수 있다.
const predicates = {increase, decrease};

//3. 함수의 매개변수에 전달할 수 있다.
//4. 함수의 반환값으로 사용할 수 있다.
function makeCounter(predicate){
  let num=0;

  return function(){
    num=predicate(num);
    return num;
  };
}

//3. 함수는 매개변수에게 함수를 전달할 수 있다.
const increaser = makeCounter(predicates.increase);
console.log(increaser()); //1
console.log(increaser()); //2

//3. 함수는 매개변수에게 함수를 전달할 수 있다.
const decreaser = makeCounter(predicates.decrease);
console.log(decreaser()); //-1
console.log(decreaser()); //-2

일급 객체로서 함수가 가지는 가장 큰 특징은 일반 객체와 같이 함수의 매개변수에 전달할 수 있으며, 함수의 반환값으로 사용할 수도 있다는 것이다. 이는 함수형 프로그래밍을 가능케 하는 자바스크립트의 장점 중 하나다.

함수는 객체이지만 일반 객체와는 차이가 있다. 일반 객체는 호출할 수 없지만 함수 객체는 호출할 수 있다. 그리고 함수 객체는 일반 객체에는 없는 함수 고유의 프로퍼티를 소유한다.

함수 객체의 프로퍼티

함수의 모든 프로퍼티의 프로퍼티 어트리뷰를 Object.getOwnPropertyDescriptors 메서드로 확인해 보면 다음과 같다.

function square(num){
  return num*num;
}
console.log(Object.getOwnPropertyDescriptors(square));
/*{
  length: { value: 1, writable: false, enumerable: false, configurable: true },
  name: {
    value: 'square',
    writable: false,
    enumerable: false,
    configurable: true
  },
  arguments: {
    value: null,
    writable: false,
    enumerable: false,
    configurable: false
  },
  caller: {
    value: null,
    writable: false,
    enumerable: false,
    configurable: false
  },
  prototype: { value: {}, writable: true, enumerable: false, configurable: false }
}*/

//__proto__는 square 함수의 프로퍼티가 아니다
console.log(Object.getOwnPropertyDescriptor(square,'__proto__')); //undefined

//__proto__는 Object.prototype 객체의 접근자 프로퍼티다.
//square 함수는 Object.prototype 객체로부터 __proto__ 접근자 프로퍼티를 상속받는다.
console.log(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__'));
/*{
  get: [Function: get __proto__],
  set: [Function: set __proto__],
  enumerable: false,
  configurable: true
}*/

❗️이처럼 arguments, caller, length, name, prototype 프로퍼티는 모든 함수 객체의 데이터 프로퍼티다. 이들 프로퍼티는 일반 객체에는 없는 함수 객체 고유의 프로퍼티다. 하지만 proto는 접근자 프로퍼티이며, 함수 객체 고유의 프로퍼티가 아니라 Object.prototype 객체의 프로퍼티를 상속받은 것을 알 수 있다. Object.prototype 객체의 프로퍼티는 모든 객체가 상속받아 사용할 수 있다. 즉, Object.prototype 객체의 proto접근자 프로퍼티는 모든 객체가 사용할 수 있다.

arguments 프로퍼티

함수 객체의 arguments 프로퍼티 값은 arguments객체다. arguments 객체는 함수 호출 시 전달된 인수들의 정보를 담고 있는 순회 가능한 유사 배열 객체이며, 함수 내부에서 지역 변수처럼 사용된다.

❗️자바스크립트는 함수의 매개변수와 인수의 개수가 일치하는지 확인하지 않는다. 따라서 함수 호출 시 매개변수 개수만큼 인수를 전달하지 않아도 에러가 발생하지 않는다.

function multiply(num1,num2){
  console.log(arguments);
  return num1*num2;
}

console.log(multiply(3,4)); //[Arguments] { '0': 3, '1': 4 } , 12
console.log(multiply()); //[Arguments] {}, NaN
console.log(multiply(3)); //[Arguments] { '0': 3 }, NaN
console.log(multiply(3,4,5)); //[Arguments] { '0': 3, '1': 4, '2': 5 } ,12

❗️함수를 정의할 때 선언한 매개변수는 함수 몸체 내부에서 변수와 동일하게 취급된다. 즉 함수가 호출되면 함수 몸체 내에서 암묵적으로 매개변수가 선언되고 undefined로 초기화된 이후 인수가 할당된다.

그렇다고 초과된 인수가 그냥 버려지는 것은 아니다. 모든 인수는 암묵적으로 arguments 객체의 프로퍼티로 보관된다. 위 예제를 브라우저 콘솔에서 실행해 보자.

arguments 객체는 인수를 프로퍼티 값으로 소유하며 프로퍼티 키는 인수의 순서를 나타낸다. arguments 객체의 callee 프로퍼티는 호출되어 arguments 객체를 생성한 함수, 즉 함수 자신을 가리키고 arguments 객체의 length 프로퍼티는 인수의 개수를 가리킨다.

arguments 객체의 Symbol(Symbol.iterator)프로퍼티

arguments 객체의 Symbol(Symbol.iterator) 프로퍼티는 arguments 객체를 순회 가능한 자료구조인 이터러블로 만들기 위한 프로퍼티다. Symbol.iterator를 프로퍼티 키로 사용한 메서드를 구현하는 것에 의해 이터러블이 된다.

function multiply(x,y){
  //이터레이터
  const iterator = arguments[Symbol.iterator]();
  console.log(iterator.next()); //{ value: 3, done: false }
  console.log(iterator.next()); //{ value: 4, done: false }
  console.log(iterator.next()); //{ value: 5, done: false }
  console.log(iterator.next()); //{ value: undefined, done: true }

  return x*y;
}
console.log(multiply(3,4,5)); //12

선언된 매개변수의 개수와 함수를 호출할 때 전달하는 인수의 개수를 확인하지 않는 자바스크립트의 특성 때문에 함수가 호출되면 인수 개수를 확인하고 이에 따라 함수의 동작을 달리 정의할 필요가 있을 수 있다. 이때 유용하게 사용되는 것이 arguments 객체다.

arguments 객체는 매개변수 개수를 확정할 수 없는 가변 인자 함수를 구현할 때 유용하다.

function sum(){
  let res=0;
  for(let i=0;i<arguments.length; i++){
     res += arguments[i];
  }
  return res;
}
console.log(sum()); //0
console.log(sum(4,5)); //9
console.log(sum(4,5,6)); //15

❗️arguments 객체는 배열 형태로 인자 정보를 담고 있지만 실제 배열이 아닌 유사 배열 객체다. 유사 배열 객체란 length 프로퍼티를 가진 객체로 for 문으로 순회할 수 있는 객체를 말한다.

😢유사 배열 객체는 배열이 아니므로 배열 메서드를 사용할 경우 에러가 발생한다. 따라서 Function.prototype.call, Function.prototype.apply,를 사용해 간접 호출해야 하는 번거로움이 있다.

function sum(){
  //arguments 객체를 배열로 변환
  const arr=Array.prototype.slice.call(arguments);
  return arr.reduce(function(pre, cur){
    return pre+cur;
  },0);
}

console.log(sum(1,2)); //3
console.log(sum(5,6,7)); //18

😎이러한 번거로움을 해결하기 위해 ES6에서는 Rest 파라미터를 도입했다.

//ES6 Rest parameter
function sum(...args){
  return args.reduce((pre, cur)=>pre+cur,0);
}
console.log(sum(1,2)); //3
console.log(sum(12,3,34));//49

length 프로퍼티

함수 객체의 length 프로퍼티는 함수를 정의할 때 선언한 매개변수의 개수를 가리킨다.

function foo(){}
console.log(foo.length); //0

function bar(x){
  return x;
}
console.log(bar.length); //1

function baz(x,y){
  return x * y;
}

console.log(baz.length); //2

name 프로퍼티

함수 객체의 name 프로퍼티는 함수 이름을 나타낸다.

//기명 함수 표현식
var namedFunc = function foo(){};
console.log(namedFunc.name); //foo

//익명 함수 표현식
var anonymousFunc = function() {};
// ES5: name 프로퍼티는 빈 문자열을 값으로 갖는다.
// ES6: name 프로퍼티는 함수 객체를 가리키는 변수 이름을 값으로 갖는다.
console.log(anonymousFunc.name);

//함수 선언문(Function declaration)
function bar(){}
console.log(bar.name); //bar

❗️"함수 선언문"에서 살펴본 바와 같이 함수 이름과 함수 객체를 가리키는 식별자는 의미가 다르다는 것을 잊지 말기 바란다. 함수를 호출할 때는 함수 이름이 아닌 함수 객체를 가리키는 식별자로 호출한다.

proto접근자 프로퍼티

모든 객체는 [[prototype]]이라는 내부 스롯을 갖는다. [[Prototype]] 내부 슬롯은 객체지향 프로그래밍의 상속을 구현하는 프로토타입 객체를 가리킨다.

proto 프로퍼티는 [[Prototype]]내부 슬롯이 가리키는 프로토타입 객체에 접근하기 위해 사용하는 접근자 프로퍼티다.[[Prototype]] 내부 슬롯에도 직접 접근할 수 없으며 proto 접근자 프로퍼티를 통해 간접적으로 프로토타입 객체에 접근할 수 있다.

const obj ={a: 1};

//객체 리터럴 방식으로 생성한 객체의 프로토타입 객체는 Object.prototype이다.
console.log(obj.__proto__ ===Object.prototype); //true

//객체 리터럴 방식으로 생성한 객체는 프로토타입 객체인 Object.prototype의 프로퍼티를 상속받는다.
//hasOwnProperty 메서드는 Object.prototype의 메서드다.
console.log(obj.hasOwnProperty('a')); //true
console.log(obj.hasOwnProperty('__proto__')); //false

prototype 프로퍼티

prototype 프로퍼티는 생성자 함수로 호출할 수 있는 함수 객체, 즉 constructor 만이 소유하는 프로퍼티다. 일반 객체와 생성자 함수로 호출할 수 없는 non-constructor에는 prototype프로퍼티가 없다.

//함수 객체는 prototype 프로퍼티를 소유한다.
let result=(function(){}).hasOwnProperty('prototype');
console.log(result); //true

//일반 객체는 prototype 프로퍼티를 소유하지 않는다.
result=({}).hasOwnProperty('prototype');
console.log(result); //false;

let func=function(){};
result=func.hasOwnProperty('prototype');
console.log(result); //true

let array= [];
result=array.hasOwnProperty('prototype');
console.log(result);//false
profile
열정으로 가득 찬 개발자 꿈나무 입니다

0개의 댓글