함수와 일급 객체

ken6666·2024년 2월 5일
0

JS

목록 보기
14/39

일급객체

  1. 무명의 리터럴로 생성할 수 있다.
  2. 변수나 자료구조에 저장할 수 있다.
  3. 함수의 매개 변수에 전달할 수 있다.
  4. 함수의 반환값으로 사용할 수 있다.

함수 객체의 프로퍼티

arguments 프로퍼티

function multiply(x, y) {
  console.log(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
  • arguments 객체는 함수 호출 시 전달된 인수들의 정보를 담고 있는 순회가능한 유사 배열 객체.
  • 함수 내부에서 지역 변수처럼 사용된다. 즉 함수 외부에서는 참조할 수 없다.
  • 초과된 인수는 그냥 버려지는 것이 아닌 암묵적으로 argument객체의 프로퍼티로 보관된다
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
  • arguments 객체는 매개변수를 확장할 수 없는 가변 인자 함수를 구현할 때 유용하다.
function sum() {
  // arguments 객체를 배열로 변환
  const array = Array.prototype.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
  • 유사 배열 객체는 배열이 아니므로 배열 메서드를 사용할 경우 에러가 발생한다

caller 프로퍼티

비표준 프로퍼티. caller 프로퍼티는 함수 자신을 호출한 함수를 가리킨다

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
  • argument 객체의 length 프로퍼티와 함수객체의 lenth 프로 퍼티의 값은 다를 수 있다
  • argument 객체의 length 프로퍼티는 인자의 개수를 가리킨다
  • 함수 객체의 length 프로퍼티는 매개변수를 가리킨다

name 프로퍼티

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

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

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

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 프로퍼티

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

// 일반 객체는 prototype 프로퍼티를 소유하지 않는다.
({}).hasOwnProperty('prototype'); // -> false
  • prototype 프로퍼티는 생성자 함수로 호출할 수 있는 함수 객체 constructor만이 소유하는 프로퍼티이다.
  • non-constructor에는 prototype 프로퍼티가 없다

0개의 댓글