본문 바로가기

JavaScript

[Deep dive] 18장 함수와 일급객체

18.1 일급 객체 

 

일급 객체 조건

 

1) 무명의 리터럴로 생성할 수 있다. 즉, 런타임에 생성이 가능하다

2) 변수나 자료구조(객체,배열 등)에 저장할 수 있다.

3) 함수의 매개변수에 전달할 수 있다.

4) 함수의 반환값으로 사용할 수 있다.

 

- 자바스크립트의 함수는 조건을 만족하므로 일급 객체이다.

1) 함수의 매개변수에 전달 가능

2) 함수의 반환값으로 사용 가능 

3) 함수 객체는 호출 가능

4) 일반 객체에는 없는 함수 고유의 프로퍼티 소유

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

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

const auxs = {increase, decrease};

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

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

const increaser = makeCounter(auxs.increase);
console.log(increaser()); //1
console.log(increaser()); //2

const decreaser = makeCounter(auxs.decrease);
console.log(decreaser()); //-1
console.log(decreaser()); //-2

 

18.2 함수 객체의 프로퍼티 

 

-함수 객체의 데이터 프로퍼티 

 ->argument, caller, length, name, prototype

 

- __proto__는 함수 객체 고유 프로퍼티가 아니라 Object.prototype 객체의 프로퍼티를 상속받은것

- Object.prototype 객체의 프로퍼티는 모든 객체가 상속받아 사용 가능 

function square(number) {
  return number * number;
}

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

 

18.2.1 arguments 프로퍼티 

 

- 함수 객체의 arguments 프로퍼티 값은 arguments 객체이다,

- arguments 객체는 함수 호출 시 전달된 인수(argument)들의 정보를 담고 있는 순회 가능한 (iterable) 유사 배열 객체 

 

- 자바스크립트는 함수의 매개변수와 인수의 개수가 일치하는지 확인하지 않음

- 매개변수의 개수보다 인수를 적게 전달했을 경우는 인수가 전달되지 않은 매개변수는 undefined로 초기화된 상태 유지 

- 매개변수의 개수보다 인수를 더 많이 전달한 경우 초과된 인수는 무시됨

function multifply(x,y) {
  console.log(arguments);
  return x*y;
}

console.log(multifply());
console.log(multifply(1))
console.log(multifply(1,2))
console.log(multifply(1,2,3))

- 초과된 인수는 그냥 버려지는 것은 아님

- 모든 인수는 암묵적으로 arguments 객체의 프로퍼티에 보관 

 

- arguments 객체는 인수를 프로퍼티 값으로 소유하며 프로퍼티 키는 인수의 순서를 나타냄

 

- arguments 객체의 callee 프로퍼티 

 : 호출되어 arguments 객체를 생성한 함수, 즉 함수 자신을 가리킴

 

- arguments 객체의 length 프로퍼티 

 : 인수의 개수를 가리킴

 

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

function sum() {
  let res = 0;

  //arguments 객체는 length 프로퍼티가 있는 유사 배열 객체이므로 for문으로 순회할 수 있다.
  for(let i = 0; i <arguments.length; i++) {
    res += arguments[i];
  }

  return res;
}

console.log(sum()); //0
console.log(sum(1,2)); //3
console.log(sum(1,2,3)); //6

 

유사 배열 객체 (array-like object)

 

- length 프로퍼티를 가진 객체로 for문으로 순회할 수 있는 객체

- arugments 객체는 배열형태로 인자 정보를 담고 있지만 실제 배열이 아닌 유사 배열 객체 

 

 

18.2.2 caller 프로퍼티 

 

- 함수 자신을 호출한 함수를 가리킴

- ECMAScript 사양에 포함되지 않는 비표준 프로퍼티 

 

 

18.2.3 length 프로퍼티 

 

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

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

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

function bax(x,y) {
  return x*y;
}
console.log(baz.length); //2

 

18.2.4 name 프로퍼티 

 

- 함수 객체의 name 프로퍼티는 함수 이름을 나타냄

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

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

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

 

18.2.5 __proto__ 접근자 프로퍼티 

 

- 모든 객체는 [[Prototype]]이라는 내부 슬롯을 가짐

- [[Prototype]] 내부 슬롯은 객체지향 프로그래밍의 상속을 구현하는 프로토타입 객체를 가리킴

- __proto__프로퍼티는 [[Prototype]] 내부 슬롯이 가리키는 프로토타입 객체에 접근하기 위해 사용하는 접근자 프로퍼티 

const obj = {a:1};

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

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

 

hasOwnProperty 메서드 

 

- 인수로 전달받은 프로퍼티 키가 객체 고유의 프로퍼티 키인 경우에만 true를 반환

- 상속받은 프로토타입의 프로퍼티 키인 경우 false를 반환

 

 

18.2.6 prototype 프로퍼티 

 

- 생성자 함수로 호출할 수 있는 함수 객체 즉, constructor만이 소유하는 프로퍼티 

- prototype 프로퍼티는 함수가 객체를 생성하는 생성자 함수로 호출될 때 생성자 함수가 생성할 인스턴스의 프로토타입 객체를 가리킴

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

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