일급 객체
**일급 객체**
의 조건은 다음과 같다.
- 무명의 리터럴로 생성할 수 있다.
- 변수나 자료구조등에 저장할 수 있다.
- 함수의 매개변수에 저장할 수 있다.
- 함수의 반환값으로 사용할 수 있다.
자바스크립트의 함수는 이 조건을 만족한다.
일급 객체의 예
무명의 리터럴로 생성
const increase = function () { return num++; }
함수는 자료구조등에 저장할 수 있다.
const auxs = { decrease }
변수에 함수 할당
const greet = function() { console.log("Hello, World!"); }; greet(); // "Hello, World!"
함수의 파라미터로 함수 전달
function executeFunction(callback) { callback(); } executeFunction(greet); // "Hello, World!"
함수의 반환값으로 함수 사용
function returnFunction() { return function() { console.log("This is returned function."); }; } const newFunction = returnFunction(); newFunction(); // "This is returned function."
함수 객체의 프로퍼티
function square(number) { return number * number; } console.dir(square);
{ length: { value: 1, writable: false, enumerable: false, configurable: true }, name: { value: 'square', writable: false, enumerable: false, configurable: true }, prototype: { value: {}, writable: true, enumerable: false, configurable: false } } // __proto__는 square 함수의 프로퍼티가 아니다. console.log(Object.getOwnPropertyDescriptor(square, '__proto__')) // undefined // __proto__ 는 Object.prototype 객체 접근자 프로퍼티다. 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
객체의 프로퍼티를 상속받는다. 이는 모든 객체가 사용할 수 있다.arguments
프로퍼티함수 객체의
arguments
프로퍼티 값은arguments
객체다. 즉, 함수 호출 시 전달되는 인수들의 정보를 담고 있는 순회가능한 유사배열객체다. 함수 내부에서 지역 변수 처럼 사용된다.function mutiply(x, y) { return x * y; } console.log(mutiply()); // NaN console.log(mutiply(1, 2)); // 2 console.log(mutiply(1, 2, 3)); // 2
함수가 호출되면 매개변수가 함수 몸체에 암묵적으로 선언되고 undefined로 초기화된다.
또한 인수가 전달되지 않으면 undefined상태를 유지하고 초과된 인수는 암묵적으로 argument 객체의 프로퍼티에 보관된다.
length
프로퍼티함수 객체의 length 프로퍼티는 함수를 정의할 때 선언한 매개변수의 개수를 가리킨다.
function foo(x, y) { foo.length // 2 }
name
프로퍼티함수 이름을 나타낸다. ES5에서는 비표준, ES6에서는 표준으로 되었음
익명함수 표현식의 경우 ES6와 ES5가 다르게 동작하는데 ES5에서는 빈문자열을 갖는다. 하지만 ES6에서는 암묵적으로 함수 객체를 가리키는 식별자를 값으로 갖는다.
__proto__
접근자 프로퍼티모든 객체는 [[Prototype]]이라는 내부 슬롯을 갖는다. 이는 객체 지향 프로그래밍 상속을 구현하는 프로토타입 객체를 가리킨다.
prototype
프로퍼티prototype 프로퍼티는 생성자 함수로 호출 할 수 있는 함수 객체, 즉 constructor만이 소유하는 프로퍼티다.
'Javascript' 카테고리의 다른 글
자바스크립트 - this (0) | 2024.04.17 |
---|---|
프로토타입 (0) | 2024.04.15 |
자바스크립트 - 프로퍼티 어트리뷰트(property attribute) (0) | 2024.04.09 |
자바스크립트 - var, const, let? (0) | 2024.04.09 |
자바스크립트 - 스코프 (0) | 2024.04.09 |