오늘은 함수와 일급 객체에 대해 알아보도록 한다.
일급 객체란?
위의 조건을 모두 충족하는 것이 일급 객체! (다할 수 있는 만능이란 뜻인 것 같다)
그렇다면 우리가 알고 있는 것들 중 일급 객체인 것들은?
함수는 일급 객체이다 (first class object)
// *딥다이브 예제로 나온 더하기, 빼기 함수
// 1. 무명으로 생성할 수 있다
// 2. 변수에 넣을 수 있다
const increase = function(num){
return ++num;
};
const decrease = function(num){
return --num;
};
// 3. 객체에 저장할 수 있다
const auxs = {increase, decrease};
// 4. 함수의 매개변수에 전달할 수 있다.
const increaser = makeCounter(auxs.increase);
console.log(increaser()); // 1
console.log(increaser()); // 2
함수는 일반 객체와 다른점이 있다. 일반 객체는 호출할 수 없지만 함수 객체는 호출할 수 있다.
// 객체는 접근하는 것. 호출은 불가!
let animals = {
name : 'lion',
sound : 'roar'
}
function makeAnimal(name, sound){
return name + sound;
}
makeAnimal(animals.name, animals.sound);
// 'lionroar'
//makeAnimal을 호출하여 사용
함수 객체는 함수 고유의 프로퍼티를 가지고 있다!
function jiyun(money){
return money + '억원';
}
console.dir(jiyun);
console.log(Object.getOwnPropertyDescriptors(jiyun));
위의 코드를 실행하면 함수객체인 'jiyun'의 arguments, caller, length, name, prototype에 대한 정보가 표시된다.
위의 다섯가지는 일반 객체에 없는 데이터 프로퍼티이다.
일반 객체인 'animals'는 위의 프로퍼티가 나오지 않는다.
arguments
*함수에서 선언된 매개변수보다 인수를 적게 전달했을경우엔 undefined,
인수를 더 많이 전달한 경우 초과 인수는 무시된다.
function jiyun(a, b) {
return a+b
}
jiyun(1); //undefined
jiyun(1,2,3) // 3 (3은 무시)
함수의 argument는 1,2 로 인자가 많으면 무시된다.
arguments 객체
arguments 객체를 활용하면 이러한 특성을 보완할 수 있다.
아큐먼트 객체는 매개변수 개수가 정해지지 않은 '가변 인자 함수'를 만들 때 좋다.
function sumString(){
let string = '';
for (let i = 0; i < arguments.length; i++){
string += arguments[i];
}
return string;
}
sumString('hi');
//'hi'
sumString('hi', 'jiyun', 'nice to meet you');
// 'hijiyunnice to meet you'
함수의 length 프로퍼티
length 프로퍼티는 함수를 정의할 때 선언한 매개변수를 가리킨다.
function snake(a, b, c, d) {
console.log(snake.length);
}
snake(); //4
함수의 name 프로퍼티
name 프로퍼티는 함수의 이름을 알려준다.
let named = function rabbit(a, b, c, d) {
console.log(named.name);
} //rabbit (기명함수)
let anonymous = function (a, b, c, d) {
console.log(anonymous.name);
} //anonymous (익명함수일 경우, 변수의 이름 표시)
function cat (a, b, c, d) {
console.log(cat.name);
} //cat
함수의 proto접근자 프로퍼티
proto프로퍼티는 내부 슬롯이 가리키는 프로토타입 객체에 접근하기 위해 사용하는 접근자 프로퍼티! 직접 접근은 불가하나 간접적으로 접근한다.
const jiyun = { age : 10 };
console.log(obj.__proto__ === Object.prototype); //true
console.log(obj.hasOwnProperty('age')); //true
console.log(obj.hasOwnProperty('__proto__')); //false
hasOwnProperty는 프로퍼티 키가 객체 고유의 프로퍼티 키인 경우에만 true를 반환하고, 프로토타입의 프로퍼티 키인 경우 false를 반환한다.
prototype 프로퍼티
해당 프로퍼티는 생성자 함수로 호출할 수 있는 함수 객체 (constructor)만이 소유하는 프로퍼티이다.
(function () {}).hasOwnProperty('prototype'); //true
({}).hasOwnProperty('prototype'); //false
QUIZ!!!!
// 1. 함수는 몇급객체?
// 2.
function apple(){
let string = '';
for (let i = 0; i < arguments.length; i++){
string += arguments[i];
}
return string;
}
function banana(a, b, c){
return a + b + c;
}
//무엇이 온전히 찍힐까?
apple('사과', '맛잇', '나', '?');
banana('바나나', '맛잇', '음', '?');