자바스크립트 언어 기본 - 함수지향
자바스크립트 언어 기본 - Javscript
12. 함수지향 - 유효범위
12.1 전역변수와 지역변수
유효범위 (scope)는 변수의 수명을 의미한다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
var vscope = 'global';
function fscope() {
var vscope = 'local';
alert(vscope);
}
</script>
</body>
</html>
함수 밖에서 변수를 선언하면 그 변수는 전역변수이다. 애플리케이션 전역에서 접근 가능하다.
12.2 유효범위의 효용성
function a (){
var i = 0; //결과 01234
// i=0; // 결과 무한반복
}
for(var i = 0; i < 5; i++){
a();
document.write(i);
}
12.3 전역변수를 사용하는 법
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
var MYAPP = {}
MYAPP.calculator = {
'left' : null,
'right' : null
}
MYAPP.coordinate = {
'left' : null,
'right' : null
}
MYAPP.calculator.left = 10;
MYAPP.calculator.right = 20;
function sum() {
return MYAPP.calculator.left + MYAPP.calculator.right;
}
document.write(sum());
</script>
</body>
</html>
불가피하게 전역변수를 사용하는 경우 하나의 객체를 전역변수로 만들고 객체의 속성으로 관리하는 것
익명함수로 만들어서 전역변수가 아예 없는 소스 코드를 만들 수도 있다.
12.4 유효범위의 대상
java에서는 {} 안에 변수를 선언할 경우 {}에서만 쓸 수 있지만
자바스크립트는 {} 밖에서도 쓸 수 있다.
자바스크립트에서의 지역변수는 함수 내에서만 유효하다.
12.5 정적 유효범위
자바스크립트는 함수가 선언된 시점에서 유효범위라고 한다. 이를 정적, 렉시컬 유효범위라고 한다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
var i = 5;
function a() {
var i = 10;
b();
}
function b() {
document.write(i);
}
a();
</script>
</body>
</html>
결과는 5이다.
선언된 시점에서 사용할 수 있는 변수를 끌고 오지, 함수가 호출될 때의 시점에서 변수를 끌고 오는 것이 아니다.
즉 사용될 때가 아닌 정의될 때의 변수가 사용됨
13. 값으로서의 함수와 콜백
13.1 함수의 용도 - 1
javascript는 함수도 객체다.
function a() {}는 아래와 의미가 같다.
var a = function() {}
a = {
b : function() {
}
};
함수는 값이라서 객체 안에 저장될 수 있고, 객체의 속성 값으로 담겨진 함수를 메소드라고 부른다.
function cal(func, num) {
return func(nul)
}
function increase(num) {
return num+1
}
function decrease(num) {
return num-1
}
alert(cal(increase, 1));
alert(cal(decrease, 1));
13.2 값으로서의 함수와 콜백 - 함수의 용도 2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
function cal(mode) {
var funcs = {
'plus': function(left, right) {return left+right},
'minus': function(left, right) {return left - right}
}
return funcs(mode);
}
alert(cal('plus')(2, 1));
alert(cal('minus')(2, 1));
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
var process = [
function(input) {return input + 10; },
function(input) {return input * input; },
function(input) {return input / 2;}
];
var input = 1;
for(var i=0; i<process.length; i++) {
input = process[i](input);
}
</script>
</body>
</html>
변수, 매개변수, 리턴값에 쓸 수 있는 값을 자바스크립트에서 first-class citizen(object, value ...)라고도 부른다.
13.3 값으로서의 함수와 콜백 - 콜백이란?
처리의 위임 : 함수가 수신하는 인자가 함수인 경우.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
var numbers = [20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
var sortfunc = function(a, b) {
console.log(a, b);
if(a>b) {
return 1;
}else if(a<b) {
return -1;
} else {
return 0;
}
}
console.log(numbers.sort(sortfunc));
</script>
</body>
</html>
13.4 비동기 콜백과 Ajax
비동기 처리 : 시간이 오래걸리는 작업이 있을 때 이 작업이 완료된 후에 처리해야 할 일을 콜백으로 지정해 해당 작업이 끝났을 때 미리 등록한 작업을 실행하도록 할 수 있다.
Ajax (asynchronous javascript and XML) 에서 비동기 처리를 많이 사용한다.
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.get('./datasource.json.js', function(result){
console.log(result);
}, 'json');
</script>
</body>
</html>
14. 클로저
14.1 내부함수, 외부함수
클로저는 내부함수가 외부함수의 맥락에 접근할 수 있는 것을 가리킨다.
outter 내부에 함수 inner가 정의되어 있다.
내부함수는 외부함수의 지역변수에 접근할 수 있다.
14.2 클로저란?
클로저는 내부함수와 밀접한 관계를 가지고 있는 주제이다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
function outter() {
var title = 'coding everybody';
return function() {
alert(title);
}
}
inner = outter();
inner();
</script>
</body>
</html>
여기서 inner는 function() {alert(title);}를 받는다.
그러나 inner를 실행시켜서 outter에 있는 title 변수에 접근할 수 있는 것이다.
14.3 private variable
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
function factory_movie(title) {
return {
get_title : function() {
return title;
},
set_title : function(_title) {
title = _title
}
}
}
ghost = factory_movie('Ghost in the shell');
matrix = factory_movie('Matrix');
console.log(ghost.get_title());
ghost.set_title("corrected");
console.log(ghost.get_title());
</script>
</body>
</html>
위 코드로 private variable을 사용할 수 있다.
각각의 객체에 title이라는 변수가 담기는데, title는 외부 함수의 지역 변수이다.
즉, return 받은 객체에서 직접적으로 title에 접근할 수 없지만, 내부 메소드를 통해서만 접근할 수 있게 된다.
14.4 클로저의 응용
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
var arr = [];
for var i = 0; i<5; i++) {
arr[i] = function() {
return i;
}
}
for(var index in arr) {
console.log(arr[index]());
}
</script>
</body>
</html>
<script type="text/javascript">
var arr = [];
for var i = 0; i<5; i++) {
arr[i] = function(id) {
return function() {
return id;
}
}(i);
}
for(var index in arr) {
console.log(arr[index]());
}
</script>
15. arguments
15.1 arguments 소개
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
function sum() {
var i, _sum = 0;
for(i=0; i<arguments.length; i++) {
document.write(i + ' : ' + arguments[i] + '<br/>');
_sum += argumnets[i];
}
return _sum;
}
document.write('result : ' + sum(1, 2, 3, 4));
</script>
</body>
</html>v
변수에 담긴 숨겨진 유사 배열로, 함수를 호출할 때 입력한 인자를 담는다.
15.2 매개변수의 수 - function length
function zero() {
console.log(
'one.length', one.length,
'arguments', arguments.length
);
}
one('val1', 'val2'); //one.length 1 arguments 2
16. 함수의 호출
16.1 apply 소개
함수는 객체이므로, 사용자가 정의한 기능 말고 내장 메소드를 가진다.
16.2 apply 사용
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
o1 = {val1: 1, val2:2, val3:3}
o2 = {v1:10, v2:50, v3:100, v4:25}
function sum() {
var _sum = 0;
for(name in this) {
_sum += this[name];
}
return _sum;
}
alert(sum.apply(o1));
alert(sum.apply(o2));
</script>
</body>
</html>
o1을 apply의 인자로 두면 함수의 this가 그 객체가 된다. 즉 var this = o1;이 되는 것!