34
스스스스 스스스 CH.02. JS function

Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

Embed Size (px)

Citation preview

Page 1: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

스파르탄 스터디CH.02. JS func-tion

Page 2: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

1.기본개념부터 잡아보자

2.호출패턴에 따라 달라지는 this

3.상속을 가능하게 해주는 Prototype

4.다른 언어와 다른 유효범위 Scope

+@ 재귀함수를 구현하는 3 가지 방법

Page 3: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

1.기본개념부터 잡아보자2. 호출패턴에 따라 달라지는 this

3. 상속을 가능하게 해주는 Prototype

4. 다른 언어와 다른 유효범위 Scope

+@ 재귀함수를 구현하는 3 가지 방법

Page 4: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

함수호출되거나 실행될 수 있는 자바스크립트 코드 블록모듈화의 근간자바스크립트는 함수형 언어일급객체 (First class citizen)

1. 기본개념

Page 5: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

함수 vs. 메서드console.dir() 은 함수일까 ? 메서드일까 ?

function funcA() { /* 코드 블록 */ }

vs.var objA = { funcA : function() { /* 코드 블록 */ }}

1. 기본개념

Page 6: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

함수 vs. 메서드함수를 객체의 속성에 저장하는 경우=> 메서드 (method)

console.dir() 의 dir 역시 console 객체의 하나의 속성

1. 기본개념

Page 7: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

내장함수 (built-in func-tion)

미리 생성되어 있는 함수들parseInt(), Math.exp() 등등

1. 기본개념

Page 8: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

함수의 종류FunctionDeclaration vs. FunctionExpression

funcA();function funcA() { console.log('funcA has called');} // 호출됨

* FunctionDeclaration 은 Hoisting 이 발생한다 . ( 단 , 정식명칭은 아니다 .)

1. 기본개념

Quiz.

funcB();var funcB = function() { console.log('funcB has called');}; // 에러

Page 9: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

Quiz.

console.log(a);var a = 1;var a = function(){};console.log(a);

1. 기본개념

console.log(a);var a = 1;function a() {};console.log(a);

console.log(a);function a() {};var a = 1;console.log(a);

각각의 출력 결과는 ?

Page 10: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

Quiz.

console.log(a);var a = 1;var a = function(){};console.log(a);

// undefined// function (){}

1. 기본개념

console.log(a);var a = 1;function a() {};console.log(a);

// function a() {}// 1

console.log(a);function a() {};var a = 1;console.log(a);

// function a() {}// 1

Page 11: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

그 외의 함수들즉시실행함수(function(){ console.log("Right now!")})();

1. 기본개념

중첩된 함수 혹은 내부함수function a() { function b() { }}

=> closure

Page 12: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

함수 전달인자 - argumentsfunction maxNum(/* 어떤 값이 들어와도 상관 없음 */) { var max = Number.NEGATIVE_INFINITY; for(var idx in arguments) { if(!isNaN(arguments[idx]) && arguments[idx]>max) { max = Number(arguments[idx]); } } return max;}

maxNum(1, 21, 3, undefined, 5, 123, false, '1234', 'test');

=> 가변전달인자 varargs(variable length arguments)

1. 기본개념

Page 13: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

Arguments 객체- 함수 내부에 존재하는 객체

function dirArgu(/* 파라미터 선언 없음 */) { console.dir(arguments);}

dirArgu(1);

dirArgu(1,2,3,4,5,6,7);

1. 기본개념

Page 14: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

1.기본개념부터 잡아보자

2.호출패턴에 따라 달라지는 this3. 상속을 가능하게 해주는 Prototype

4. 다른 언어와 다른 유효범위 Scope

+@ 재귀함수를 구현하는 3 가지 방법

Page 15: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

호출패턴과 this

1. 메서드 호출 패턴- 호출하는 패턴에 따라 this 라는 추가적인 매개변수를 다르게 초기화 한다 .

var objA = { sum : 0 , add : function(addVal) { this.sum += addVal; return this.sum; }}

objA.sum;objA.add(2);objA.add(3);

var directAddCall = objA.add;directAddCall(2);

this === objA

2. 호출패턴에 따라 달라지는 this

this === window

★ This -> 호출한 함수가 속한 오브젝트를 참조

Page 16: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

2. 함수 호출function funcA() { console.dir(this);};

console.dir(funcA());

2. 호출패턴에 따라 달라지는 this

this === window

function funcA() { "use strict"; console.dir(this);};

funcA();window.funcA();

this === undefinedthis === window

Page 17: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

3. 생성자 호출function FuncA() {};var funcB = new FuncA();

FuncA.prototype.checkThis = function(){ console.dir(this);};

funcB.checkThis();

2. 호출패턴에 따라 달라지는 this

this === FuncA

Page 18: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

4. call 과 applyfunction A(a,b,c) {console.log(this.x, this.y, a, b, c);}

A();

A.call({x:1,y:2});

A.apply({x:1,y:2},[3,4,5]);

명시적으로 this 에 map-ping 시킬 프로퍼티들을 넘길 수 있다

2. 호출패턴에 따라 달라지는 this

Page 19: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

+ bind 를 통한 this map-pingvar newA = A.bind({x:3,y:4})

var newA2 = A.bind({x:3,y:4,a:5})

2. 호출패턴에 따라 달라지는 this

call, apply -> 호출시점에 일시적인 매핑bind -> 영구적인 Binding

Page 20: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

1.기본개념부터 잡아보자2. 호출패턴에 따라 달라지는 this

3.상속을 가능하게 해주는 Prototype4. 다른 언어와 다른 유효범위 Scope

+@ 재귀함수

Page 21: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

함수의 프로토타입 상속function FuncA() {}var funcA1 = new FuncA();

console.dir(funcA1);

FuncA.prototype.addedMethod = function(){ console.log("I'm added"); };

console.dir(funcA1);

3. 상속을 가능하게 해주는 Prototype

=> __proto__ 는 생성자의 prototype 을 바라보고 있다 .

Page 22: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

* prototype chaining 맛보기var a = { func : function(){ console.log(this.val); }};

var b = Object.create(a);var c = Object.create(b);var d = Object.create(c);var e = Object.create(d);

b.val = 'b.val';a.val = ‘a.val‘;e.func(); // b.val

e .__proto__ .__proto__ .__proto__ .__proto__ === a; // true

3. 상속을 가능하게 해주는 Prototype

Page 23: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

1.기본개념부터 잡아보자2. 호출패턴에 따라 달라지는 this

3. 상속을 가능하게 해주는 Prototype

4. 다른 언어와 다른 유효범위 Scope+@ 재귀함수를 구현하는 3 가지 방법

Page 24: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

Quiz.function aa() { var a = 1; function b() { var a = 2; c(); } function c() { console.log(a); } b();}

aa();

a = ?

4. 다른 언어와 다른 유효범위 Scope

Page 25: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

Quiz. 항목별 유효범위 4. 다른 언어와 다른 유효범위 Scope

function outer() { debugger; inner(); var a = 1; function inner() { var x = 2; } var b = 2; if(a==1) { var c = 3; } console.log(c);}outer();

항목별 Scope 는 어떻게 될까 ?

outer()inner()x, a, b, c

Page 26: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

항목별 유효범위

Scope 결정요소 :

어디에 선언되었느냐 ?

변수냐 ? 함수냐 ?

4. 다른 언어와 다른 유효범위 Scope

function outer() { debugger; inner(); var a = 1; function inner() { var x = 2; } var b = 2; if(a==1) { var c = 3; } console.log(c);}outer();

항목별 Scope : ( 순서대로 )outer(), inner(), x, a, b, c

!! If 블록을 넘어간다 .

* JavaScript 의 Scope 는 블록단위가 아니라 함수 단위

Page 27: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

블록 vs. 함수 유효범위C, Java 등의 언어의 유효범위 : { } (Block)

if(window) { var x =123;}console.log(x);

블록이 끝났다고 (}) 유효범위가 끝나지 않는다 .Þ JavaScript 의 유효범위 : 함수

4. 다른 언어와 다른 유효범위 Scope

Page 28: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

1.기본개념부터 잡아보자2. 호출패턴에 따라 달라지는 this

3. 상속을 가능하게 해주는 Prototype

4. 다른 언어와 다른 유효범위 Scope

+@ 재귀함수를 구현하는 3 가지 방법

Page 29: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

Quiz.function factorial() { return function(x) { if (x <= 1) return 1; else return x * arguments.callee(x-1); };}

factorial()(5);

+@ 재귀함수를 구현하는 3 가지 방법

arguments? callee? 괄호는 왜 2 개 ?

Page 30: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

Quiz.function factorial() { return function(x) { if (x <= 1) return 1; else return x * arguments.callee(x-1); };}

factorial()(5);

+@ 재귀함수를 구현하는 3 가지 방법

arguments? -> 함수가 실행될 때 생성되는 객체callee? -> 자신을 호출한 객체괄호는 왜 2 개 ? -> 첫 번째 괄호는 실행 후에 function(x) 를 리턴 . 두 번째 괄호를 통해 function(x) 를 실행 .

Page 31: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

재귀 - Function Declara-tionfunction factorial(x) { if (x <= 1) return 1; else return x * factorial(x-1);}

factorial(5);

=> 어느 곳에서든지 이름으로 호출 가능

+@ 재귀함수를 구현하는 3 가지 방법

Page 32: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

재귀 – 메서드 (Function Expres-sion)var factorial = function recurs(x) { if (x <= 1) return 1; else return x * recurs(x-1);}

factorial(5);=> 익명 함수에 이름을 주면 함수 내에서 사용할 수 있다 .

+@ 재귀함수를 구현하는 3 가지 방법

Page 33: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

재귀 – arguments.callee (depre-cated)

var factorial = function(x) { if (x <= 1) return 1; else return x * arguments.callee(x-1);}

factorial(5);

=> 함수가 호출되는 시점에 자신을 호출한 객체를 arguments.callee 에 할당한다 .

+@ 재귀함수를 구현하는 3 가지 방법

Page 34: Javascript 함수(function) 개념, 호출패턴, this, prototype, scope

참고자료- http://www.ecma-international.org/ecma-262/5.1/

- https://developer.mozilla.org/en-US/docs/Web/JavaS

cript/Reference/Operators/this

- 자바스크립트 완벽가이드 데이비드 플래너건- 자바스크립트 핵심 가이드 더글라스 크락포드- 자바스크립트 닌자 비급 존 레식 , 베어 바이볼트- 몰입 ! 자바스크립트 김영보

2. 호출패턴에 따라 달라지는 this