JS/[책] 모던 JS deep dive

18장. 함수와 일급 객체

web_seul 2022. 12. 21. 04:22
반응형

18.1 일급 객체

일급객체의 조건

1. 무명의 리터럴로 생성 가능(런타임에 생성 가능)

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

3. 함수의 매개변수에 전달 가능

4. 함수의 반환값으로 사용가능

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

//2. 객체에 저장가능
const auxs = {increase, decrease};

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

//3. 함수는 매개변수에 함수 전달 가능
const increaser = makeCounter(auxs.increase);
console.log(increaser());	//1
console.log(increaser());	//2

//3. 함수는 매개변수에 함수 전달 가능
const decreaser = makeCounter(auxs.decrease);
console.log(decreaser());	//-1
console.log(decreaser());	//-2

함수가 일급 객체라는 것은 함수를 객체와 동일하고 사용가능하다는 의미, 객체는 값이므로 함수는 값과 동일하게 취급 가능, 따라서 함수는 값을 사용할 수 있는 곳은 리터럴로 정의 가능하며 런타임에 함수객체로 평가됨,

일반 객체와 같이 함수의 매개변수에 전달 가능, 함수의 반환값으로 사용 가능, 일반객체는 호출이 불가능하나 함수 객체는 호출 가능, 함수 객체는 함수 고유의 프로퍼티를 소유

 

18.2 함수 객체의 프로퍼티

function square(number){
  return numbre * number;
}
//함수 객체 내부 확인
console.dir(square);

 

//함수의 모든 프로퍼티의 프로퍼티 어트리뷰트 확인
console.log(Object.getOwnPropertyDescriptors(square));

 

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

 

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

 

=> arguments, caller, length, name, prototype 프로퍼티는 모두 함수 객체 고유의 데이터 프로퍼티, __proto__는 접근자 프로퍼티이며 함수 객체 고유의 프로퍼티가 아닌 Object.prototype객체의 프로퍼티 상속, Object.prototype객체의 __proto__접근자 프로퍼티는 모든 객체가 사용 가능

 

18.2.1 arguments 프로퍼티 : 함수 객체의 arguments프로퍼티 값은 arguments객체, arguments 객체는 함수 호출 전달된 인수들의 정보를 담은 순회 가능한 유사 배열 객체, 함수 내부에서 변수처럼 사용(함수 외부에서 참조x)

함수 객체의 arguments 프로퍼티는 ES3 표준에서 폐지, Function arguments와 같은 사용법은 권장되지 않으며 함수 내부에서 지역 변수처럼 사용할 수 있는 arguments객체를 참조

//함수의 매개변수와 인수의 개수가 일치하는지 확인x
//함수 호출시 매개변수와 인수의 개수가 일치하지않아도 Error x
function multiply(x, y){
  console.log(arguments);	//console.log(multiply arguments)가 아닌
  				//함수 내부에서 참조
  return x * y;
}
console.log(multiply());	//NaN
console.log(multiply(1));	//NaN
console.log(multiply(1, 2));	//2
console.log(multiply(1, 2, 3));	//2

 

함수를 정의시 선언된 매개변수(x, y)는 함수 몸체 내부에서 변수와 동일하게 취급, 함수가 호출되면 함수 몸체 내에서 암묵적으로 매개변수 선언, undefined로 초기화, 인수 할당

매개변수와 인수의 개수 일치여부를 확인하지 않음 : 선언된 매개변수의 개수보다 인수를 적게 전달했을 경우 console.log(multiply()), console.log(multiply(1))) 매개변수는 undefined로 초기화된 상태유지, 매개변수의 개수보다 많이 전달한 경우 (console.log(multiply(1, 2, 3))) 초과된 인수는 무시되나 버려지는 것이 아닌 암묵적으로 arguments 객체의 프로퍼티로 보관

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

* arguments 객체의 Symbol(Symbol.iterator) 프로퍼티 : 객체를 순회가능한 자료구조인 이터러블로 만들기 위한 프로퍼티

function multiply(x, y){
  const iterator = arguments[Symbol.iterator]();
  
  console.log(iterator.next());	//{value:1, done:false}
  console.log(iterator.next());	//{value:2, done:false}
  console.log(iterator.next());	//{value:3, done:false}
  console.log(iterator.next());	//{value:undefined, done:true}
  
  return x * y;
}

multiply(1, 2, 3);

 

-> 매개변수의 개수와 함수 인자의 개수를 확인하지 않기때문에 가변 인자함수(매개변수 개수를 확정할 수 없는)를 구현할 때 arguments 객체 사용, arguments객체는 배열형태로 인자 정보를 담지만 실제 배열이 아닌 유사배열객체(length 프로피트를 가진 객체, for문으로 순회가능)

* 유사 배열객체와 이터러블 : ES6 도입된 이터레이션 프로토콜을 준수하면서 순회 가능한 자료구조, ES5까지 arguments객체는 유사배열객체로 구분, ES6부터는 유사배열객체이자 이터러블

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

 

but, 유사배열객체는 배열이 아니므로 배열 메서드 사용시 Error발생, Function.prototpye.call, Function.prototype.apply를 사용해 간접 호출해야함 -> ES6 Rest파라미터 도입 

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

console.log(sum(1, 2));	//3
console.log(sum(1, 2, 3, 4, 5));	//15


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

 

18.2.2 caller 프로퍼티 : 비표준 프로퍼티, 함수 자신을 호출한 함수

function foo(func){
  return func();
}

function bar(){
  return 'caller :'+ bar.caller;
}

//브라우저 실행(node.js 환경에서와 다른 결과 48장 모듈 참고)
console.log(foo(bar));	//caller : function foo(func){..}, bar 자신을 호출한 함수 = foo
console.log(bar());	//caller : null, bar 자신을 호출한 함수 = null

 

18.2.3 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

arguments 객체의 length 프로퍼티 : 인자의 개수
함수 객체의 length 프로퍼티 : 매개변수의 개수

 

18.2.4 name 프로퍼티 : 함수이름, ES6 표준(익명함수 표현식에서 name프로퍼티는 ES5 - 빈 문자열, ES6 - 함수객체를 가리키는 식별자를 값으로 가짐)

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

//익명 함수 표현식
var anonymousFunc = function() {};
console.log(anonymousFunc.name);	//anonymousFunc(ES6), ''(ES5)

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

 

18.2.5 __proto__ 접근자 프로퍼티 : 내부 슬롯이 가리키는 프로토타입 객체에 접근하기 위해 사용하는 접근자 프로퍼티, 모든 객체는 [[Prototype]]이라는 내부 슬롯을 가짐, 객체 지향 프로그래밍의 상속을 구현하는 프로토타입 객체를 가리킴(19장 프로토타입 참고), 직접접근x

const obj = [a:1};

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

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

* hasOwnProperty 는 인수로 전달받은 프로퍼티 키가 객체 고유의 프로퍼티 키인 경우에만 true반환, 상속받은 프로퍼티키는 false반환 

 

18.2.6 prototype 프로퍼티 : 생성자 함수로 호출할 수 있는 함수 객체, constructor만이 소유하는 프로퍼티, 일반객체와 생성자 함수로 호출불가한 non-constructor에는 prototype 프로퍼티가 없음, prototype 프로퍼티는 함수가 객체를 생성하는 생성자 함수로 호출될 때 생성자 함수가 생성할 인스턴스의 프로토타입 객체를 가리킴

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

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

 

반응형

'JS > [책] 모던 JS deep dive' 카테고리의 다른 글

21장. 빌트인 객체  (0) 2023.01.10
20장. strict mode  (0) 2022.12.30
15장. let, const 키워드와 블록레벨 스코프  (0) 2022.12.21
11장. 원시값과 객체의 비교  (0) 2022.12.14
7장. 연산자  (0) 2022.12.07