// 1. 함수는 무명의 리터럴로 생성할 수 있다.
// 2. 함수는 변수에 저장할 수 있다.
const increase = function(number) {
return number + 1;
};
const decrease = function(number) {
return number - 1;
};
// 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);
increaser(); // 1
increaser(); // 2
// 3. 함수는 매개변수에 함수를 전달할 수 있다.
const decreaser = makeCounter(predicates.decrease);
decreaser() // -1
decreaser() // -2
function square(number) {
return number * number;
}
Object.getOwnPropertyDescriptors(square);
/*
{
length: { value: 1, writable: false, enumberable: false, configurable: true },
name: { value : "square", writable: false, enumberable: false, configurable: true },
arguments: { value: null, writable: false, enumberable: false, configurable: false },
caller: { value: null, writable: false, enumberable: false, configurable: false },
prototype: { value: {...}, writable: true, enumberable: false, configurable: false }
}
*/
Object.getOwnPropertyDescriptor(square, '__proto__') // undefined
Object.getownPropertyDescriptor(Object.prototype, '__proto__')
// { get: f, set: f, enumerable: false, configurable: true }
이처럼 arguments, caller, length, name, prototype 프로퍼티는 모두 함수 객체의 데이터 프로퍼티다.
이들 프로퍼티는 일반 객체에는 없는 함수 객체 고유의 프로퍼티다.
arguments 객체는 함수 호출시 전달된 인수들의 정보를 담고 있는 순회 가능한 유사 배열 객체이다.
함수 내부에서 지역 변수처럼 사용 된다. (즉, 함수 외부에서는 참조할 수 없다)
자바스크립트는 함수의 매개변수와 인수의 갯수가 일치하는지 확인하지 않는다.
함수 호출시 매개변수 개수만큼 인수를 전달하지 않아도 에러가 발생하지 않는다.
function multiply(x, y) {
return x * y;
}
multiply(); // NaN
multiply(1); // NaN
multiply(1, 2); // 2
multiply(1, 2, 3); // 2
function sum() {
let result = 0;
const argumentsLength = arguments.length;
for(var i = 0; i < argumentsLength; i++) {
result = result + arguments[i];
}
return result;
}
sum(); // 0
sum(1); // 1
sum(1, 2); // 3
sum(1, 2, 3); // 6
sum(1, 2, 3, 4); // 10
.
.
.
.
arguments 객체는 배열이 아닌 유사 배열 객체이며, 배열 메서드를 사용할 경우 에러가 발생한다.
함수 객체의 length 프로퍼티는 함수를 정의할 때 선언한 매개변수의 개수를 가리킨다.
function func1() {}
func1.length; // 0
function func2(x) { return x }
func2.length; // 1
function func3(x, y) { return x * y }
func3.length; // 2
함수 객체의 name 프로퍼티는 함수 이름을 나타낸다. (ES5, ES6 에서 동작 결과가 다르므로 주의!)
var namedFunc = function foo() {};
namedFunc.name; // foo
var anonymousFunc = function() {};
ES5) anonymousFunc.name // <- 빈 문자열
ES6) anonymousFunc.name // anonymousFunc
function bar() {}
bar.name; // bar
hasOwnProperty
const obj = { a: 1 };
obj.hasOwnProperty('a'); // true
obj.hasOwnProperty('b'); // false
prototype 프로퍼티는 생성자 함수로 호출할 수 있는 함수 객체.
즉 constructor만이 소유하는 프로퍼티다.
일반 객체와 생성자 함수로 호출할 수 없는 non-constructor에는 prototype 프로퍼티가 없다.
(function () {}).hasOwnProperty('prototype'); // true
({}).hasOwnProperty('prototype'); // false
prototype 프로퍼티는 함수가 객체를 생성하는 생성자 함수로 호출될 때 생성자 함수가 생성할 인스턴스의 프로토타입 객체를 가리킨다.
참고
- 모던 자바스크립트 Deep Dive - 18장 함수와 일급 객체