레이블이 javascript function인 게시물을 표시합니다. 모든 게시물 표시
레이블이 javascript function인 게시물을 표시합니다. 모든 게시물 표시

2015년 8월 30일 일요일

Javascript Function

Let's see javascript function and its usage. Learning test is written using Jasmine. Please refer Jasmine usage which I wrote before if you have interest it.


1. Define function and its usage


Define function in javascript is nothing special. Let's see [line 8] closely. The function can be assigned to variable. It means that function can be a argument of another function just like a variable. It is also possible call like [line 11]. It this case, The name of variable which have a function as a value would be a the name of function.


2. call by value, call by reference

If the argument is primitive type, call by value is used. If the argument is non-primitive type like array or object, call by reference is used.

3. Arguments

Javascript don't support function oveloading. See [line 6]. You can know the reason. If more arguments are used than defined when call function, the other argument which are not defined wouldn't be used. You can know what values are used as a argument using "arguments" object. Refer "func2" in following example.


4. Closure

Javascript have the concept of closure. The "inside" function is defined in "outside" and "outside" function return the "inside" function itself. Variable "a" which is argument of "outside" can be referred in "inside" function.  You can call it like [line 9] and [line 10].


5. Reference 

- MDN - https://developer.mozilla.org/en/docs/Web/JavaScript
- Jasmine - http://jasmine.github.io/2.3/introduction.html

2015년 7월 26일 일요일

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

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

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

2. call by value, call by reference
primitive type은 값(value)으로서 매개변수가 함수로 넘어간다. 배열이나 오브젝트와 같은 non-primitive type은 참조(reference)로서 매개변수가 넘어간다.

3. arguments
자바스크립트에서는 함수 오버로딩이 지원되지 않는다. 라인 6을 보면 그 이유를 알 수 있다. 함수에서 정의된 매개변수보다 많은 매겨변수를 사용하여 실제 그 함수가 호출된다면, 나머지 매개변수는 사용되지 않는다. 함수를 호출할때 어떤 값들을 매개변수로 넘겨줬는지 알고 싶을때가 있다. 이때는 "arguments" 라는 오브젝트를 참고하면 된다.  아래 예제에서의 func2 을 참고하자.

4. closure
자바스크립트에서는 closure 라는 개념을 지원한다. outside 라는 함수안에서 inside라는 함수를 정의하고, inside라는 함수 자체를 리턴한다. inside 함수에서는 outside 매개변수인 a 을 참조할 수 있다. 라인 9 와 라인 10과 같이 호출하는 것이 가능하다.

5. 참조 
- MDN - https://developer.mozilla.org/en/docs/Web/JavaScript
- Jasmine - http://jasmine.github.io/2.3/introduction.html