Skip to content
On this page

2020-03-11

Title
2020-03-11
Category
2020
Tags
Aliases
2020-03-11
Created
4 years ago
Updated
last year

객체지향 자바스크립트

MDN 문서

함수 복습

함수표현식에서 기명함수와 익명함수

javascript
var add = function sum(a, b) {
	return a + b;
};
var add = function sum(a, b) {
	return a + b;
};

여기에서 sum 가 함수 이름, add 이 함수 변수.

함수 이름은 외부 코드에서 접근 불가. (함수 내부의 재귀 호출 or 디버거에서 함수 구분을 위해 사용)

함수선언문은 함수 이름과 함수 변수가 같은 함수 표현식으로 생각하면 된다

함수 객체의 기본 프로퍼티

아래의 명령어를 실행해서 위에서 정의한 add 함수의 프로퍼티 목록을 볼 수 있다.

javascript
console.dir(add);
console.dir(add);

caller : 해당 함수를 호출한 함수에 대한 참조를 저장. (전역인 경우 null )

javascript
function some() {
	return foo();
}

function foo() {
	var a = 3;
	return bar();
}

function bar() {
	return 'caller : ' + bar.caller;
}

console.log(foo(bar)); // caller : function foo(func) {...}
console.log(bar()); // null (browser에서의 실행 결과)
function some() {
	return foo();
}

function foo() {
	var a = 3;
	return bar();
}

function bar() {
	return 'caller : ' + bar.caller;
}

console.log(foo(bar)); // caller : function foo(func) {...}
console.log(bar()); // null (browser에서의 실행 결과)

arguments : 함수를 호출할 때 전달된 인자값.

arguments 객체는 함수 호출 시 전달된 인수들의

javascript
function multiply(x, y) {
	console.log(arguments);
	return x * y;
}

multiply(); // {}
multiply(1); // { '0': 1 }
multiply(1, 2); // { '0': 1, '1': 2 }
multiply(1, 2, 3); // { '0': 1, '1': 2, '2': 3 }
function multiply(x, y) {
	console.log(arguments);
	return x * y;
}

multiply(); // {}
multiply(1); // { '0': 1 }
multiply(1, 2); // { '0': 1, '1': 2 }
multiply(1, 2, 3); // { '0': 1, '1': 2, '2': 3 }

__proto__ : 자신의 부모 역할을 하는 프로토타입 객체. 함수 객체의 부모는 Function.prototype 객체

length : 함수 정의 시 작성된 매개변수 갯수

javascript
function foo() {}
console.log(foo.length); // 0

function bar(x) {
	return x;
}
console.log(bar.length); // 1

function baz(x, y) {
	return x * y;
}
console.log(baz.length); // 2
function foo() {}
console.log(foo.length); // 0

function bar(x) {
	return x;
}
console.log(bar.length); // 1

function baz(x, y) {
	return x * y;
}
console.log(baz.length); // 2

prototype : 위의 __proto__ 와 다른 프로퍼티로 이 함수가 생성자로 사용될 때이함수를 통해서 생성된 객체의 부모 역할을 하는 프로토타입 객체를 가리킨다.

콜백 함수

개발자는 단지 함수를 등록하고 어떤 이벤트가 발생했거나 특정 시점에 도달했을 때시스템에서 호출되는 함수. (대표적으로 이벤트 핸들러 처리)

javascript
function initTmap() {
	var map = new Tmapv2.Map(
		'map', // "map" : 지도가 표시될 div의 id
		{
			center: new Tmapv2.LatLng(37.566481622437934, 126.98502302169841), // 지도 초기 좌표
			width: '100%', // map의 width 설정
			height: '452px', // map의 height 설정
			zoom: 19,
		},
	);
	//다각형
	var polygon = new Tmapv2.Polygon({
		paths: [
			new Tmapv2.LatLng(37.56661, 126.985666),
			new Tmapv2.LatLng(37.566595, 126.985985),
			new Tmapv2.LatLng(37.566512, 126.986071),
			new Tmapv2.LatLng(37.566397, 126.985894),
			new Tmapv2.LatLng(37.566395, 126.985664),
		],
		fillColor: 'pink',
		draggable: true,
		map: map,
	});
}

window.onload = initTmap;
function initTmap() {
	var map = new Tmapv2.Map(
		'map', // "map" : 지도가 표시될 div의 id
		{
			center: new Tmapv2.LatLng(37.566481622437934, 126.98502302169841), // 지도 초기 좌표
			width: '100%', // map의 width 설정
			height: '452px', // map의 height 설정
			zoom: 19,
		},
	);
	//다각형
	var polygon = new Tmapv2.Polygon({
		paths: [
			new Tmapv2.LatLng(37.56661, 126.985666),
			new Tmapv2.LatLng(37.566595, 126.985985),
			new Tmapv2.LatLng(37.566512, 126.986071),
			new Tmapv2.LatLng(37.566397, 126.985894),
			new Tmapv2.LatLng(37.566395, 126.985664),
		],
		fillColor: 'pink',
		draggable: true,
		map: map,
	});
}

window.onload = initTmap;

어제 공부했던 Tmap API, 마지막줄의 window.onload = initTmap 로 위에서 정의한 initTmap 함수를 onload 시(웹 페이지의 로딩이 끝나는 시점)에 콜백 함수로 호출하게 된다.

이러한 용도로 사용할 때, 콜백 함수를 간단하게 익명 함수로 사용한다.

html
<!DOCTYPE html>
<html>
	<body>
		<script>
			window.onload = function () {
				alert('This is the callback function.');
			};
		</script>
	</body>
</html>
<!DOCTYPE html>
<html>
	<body>
		<script>
			window.onload = function () {
				alert('This is the callback function.');
			};
		</script>
	</body>
</html>

즉시 실행 함수

함수를 정의함과 동시에 바로 실행하는 함수.

javascript
(function (name) {
	console.log('This is the immediate function --> ' + name);
})('foo');
(function (name) {
	console.log('This is the immediate function --> ' + name);
})('foo');

함수 리터럴을 괄호 () 로 감싸고 함수가 바로 호출될 수 있게 끝에 () 를 추가하고, 이 괄호 안에 인자를 넘길 수 있다.

즉시 실행 함수는 최초 한 번의 실행만을 필요로 하는 초기화 코드 부분에 사용할 수있다. (변수들의 유효 범위를 전역이 아니라 내부 함수로 감추는 효과)

즉시 실행함수는 최초 한번만 호출되며 다시 호출할 수 없다.

내부 함수

함수 내부에 정의된 함수.

클로저 생성이나 외부에서의 접근을 막고 독립적인 헬퍼 함수를 구현하는 용도로 사용

  • 내부 함수에서는 자신을 둘러싼 부모 함수의 변수에 접근 가능

  • 내부 함수는 일반적으로 자신이 정의된 부모 함수 내부에서만 호출 가능

외부에서 특정 함수 내부의 함수를 호출하는 방법

  • 부모 함수에서 내부 함수를 외부로 리턴. (클로저)

Released under the MIT License.