- 함수는 Function이라는 객체의 인스턴스다.
- Function의 메소드인 Function.apply와 Function.call이라는 메소드들을 상속하고 있다.
- 기본적인 호출 방법
function test(){
}
test();
- Function.apply
- 메소드명.(함수를 호출하는데 제공될 this의 값 (객체명), 전달될 인수들로 이루어진 배열)
만약 function sum(a,b) { return a+b; }라는 함수가 있다면
기본적으로는 sum(1,3);으로 호출하겠지만
Function의 메소드인 apply를 사용해서
sum.apply(null, [1,2]);로 호출할 수도 있다.
하지만 null의 경우에는 굳이 apply 보다는 그냥 바로 sum(1, 2);로 호출하는 것이 낫다.
var arr1 = {val1:1, val2:2, val3:3};
var arr2 = {v1:10, v2:50, v3:100, v4:25};
function sum(){
var result = 0;
for(name in this){
result += this[name];
}
return result;
}
console.log(sum.apply(arr1)) //출력 : 6
console.log(sum.apply(arr2)) //출력 : 185
//해설
/*
1. apply에 arr1나 arr2라는 배열을 넣으면 해당 배열의 데이터들이 실행하는 함수의 인자가 된다.
2. apply의 인자로 넣은 배열은 해당 함수의 this라는 변수의 값이 된다.
*/
- Function.call
- 메소드명.(현재 객체로 사용될 객체명, 인수1, 인수2, …)
apply와 비슷하며, 인자를 넣는 방식만 좀 다르다.
call의 경우에는 Java에서 객체를 초기화하는 것이라고 생각하면 편하다.
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);//this라는 객체에 Food의 인자로 받은 name과 price라는 변수를 전달
this.category = 'food';
}
var test=new Food('cheese', 5);
console.log(test.name); //출력 : cheeze