2015년 7월 26일 일요일

자바스크립트 함수의 정의 및 사용

자바스크립트에서의 함수의 정의와 사용법에 대해서 살펴본다. 프로그래밍에 대해서 어느 정도 경험이 있다고 가정한다. 학습테스트는 자바스크립트 테스트 프레임워크인 자스민을 이용해서 작성되었다. 자스민에 대한 사용법은 이 전에 작성했던 "자스민 사용법" 글을 참조하자.

1. 함수의 정의와 사용
함수의 정의는 별다를게 없다. 라인 8을 유심히 보자. 라인 8에서 변수에 함수를 저장하고 있다. 이 말은 함수를 변수처럼 자유롭게 넘겨줄 수 있다는 말이다. 그리고 라인 11에서처럼 호출하는 것도 가능하다. 이 경우에는 변수 이름이 함수의 이름이 된다고 생각하면 된다.

it("should return 'Hello'", function() {
function returnHello() {
return "Hello";
};
expect(returnHello()).toBe("Hello");
var sayHello = function() {
return "Hello";
}
expect(sayHello()).toBe("Hello");
});
//javascript don't support "Function overloading".
it("should return 'hello javascript world'", function() {
function returnHelloWithName(firstName, lastName) {
return "Hello " + firstName + " " + lastName;
};
expect(returnHelloWithName("javascript", "world")).toBe("Hello javascript world");
});
2. call by value, call by reference
primitive type은 값(value)으로서 매개변수가 함수로 넘어간다. 배열이나 오브젝트와 같은 non-primitive type은 참조(reference)로서 매개변수가 넘어간다.

it("call by value if argument is primitive type", function() {
var hello = "hi";
expect(hello).toBe("hi");
function sayHello(hello) {
hello = "hello";
return hello;
}
sayHello(hello);
expect(hello).toBe("hi");
});
it("call by reference if argument is non-primitive type", function() {
var arayHello = ["hi", "hello", "olleh"];
expect(arayHello[0]).toBe("hi");
function sayHello(arayHello) {
arayHello[0] = "good day";
return arayHello;
}
sayHello(arayHello);
expect(arayHello[0]).toBe("good day");
});
3. arguments
자바스크립트에서는 함수 오버로딩이 지원되지 않는다. 라인 6을 보면 그 이유를 알 수 있다. 함수에서 정의된 매개변수보다 많은 매겨변수를 사용하여 실제 그 함수가 호출된다면, 나머지 매개변수는 사용되지 않는다. 함수를 호출할때 어떤 값들을 매개변수로 넘겨줬는지 알고 싶을때가 있다. 이때는 "arguments" 라는 오브젝트를 참고하면 된다.  아래 예제에서의 func2 을 참고하자.

it("arguments", function() {
var func1 = function(a, b) {
return a + " " + b;
}
expect(func1("hi", "there")).toBe("hi there");
expect(func1("hi", "there", "good")).toBe("hi there");
var func2 = function() {
var returnVal = "";
for (i = 0; i < arguments.length; i++) {
returnVal += arguments[i];
}
return returnVal;
}
expect(func2("hi", "there", "good")).toBe("hitheregood");
});
4. closure
자바스크립트에서는 closure 라는 개념을 지원한다. outside 라는 함수안에서 inside라는 함수를 정의하고, inside라는 함수 자체를 리턴한다. inside 함수에서는 outside 매개변수인 a 을 참조할 수 있다. 라인 9 와 라인 10과 같이 호출하는 것이 가능하다.

it("closure", function() {
function outside(a) {
return function inside(b) {
return a * b;
}
};
var func = outside(2);
expect(func(4)).toBe(8);
expect(outside(3)(2)).toBe(6);
});
it("complex closure", function() {
var buyItem = function(name) {
var maker;
return {
setName: function(newName) {
name = newName;
},
getName: function() {
return name;
},
getMaker: function() {
return maker;
},
setMaker: function(newMaker) {
maker = newMaker
}
}
}
var item = buyItem("mac");
expect(item.getName()).toBe("mac");
item.setName("mac book");
expect(item.getName()).toBe("mac book");
item.setMaker("apple");
expect(item.getMaker()).toBe("apple");
});
5. 참조 
- MDN - https://developer.mozilla.org/en/docs/Web/JavaScript
- Jasmine - http://jasmine.github.io/2.3/introduction.html

댓글 없음:

댓글 쓰기