SlideShare a Scribd company logo
헷갈리는 자바스크립트 정리 
by 이은숙 
Page 1
Page 2 
목차 
자바스크립트 함수란 ? 
함수 내의 this 와 유효범위는 ? 
Closure 란 ? 
Prototype 이란 ?
자바스크립트 함수는 first-class object 이다 ? 
first-class object : An entity that can be constructed at run-time, 
passed as a parameter, returned from a subroutine, 
or assigned into a variable. - http://en.wiktionary.org/wiki/first-class_ 
Page 3 
object 
자바스크립트 함수 == first-class Object 
위의 세 가지 방법을 함수로 할 수 있다 !
자바스크립트 함수는 first-class object 이다 ? 
Page 4 
1. passed as a parameter 
function func(callback ) { 
callback(); 
}; 
func(function () { console.log("I am function"); } ); 
2. returned from a subroutine 
function func() { 
return function () { console.log("I am function"); } 
}; 
func()(); 
3. assigned into a variable 
var func = function () { console.log("I am function"); } 
func();
Inside a function, the value of this depends on how the function is 
called. -https://developer.mozilla.org/en- 
US/docs/Web/JavaScript/Reference/Operators/this 
함수가 어떻게 호출되느냐에 따라 달 
라진다 ! 
Page 5 
함수내에서 this 는 어디를 가리키는가 ?
함수내에서 this 는 어디를 가리키는가 ? 
1. 함수 생성 후 호출하였을 경우 – 전역 객체 (window) 를 가르킨다. 
var isAccess = true; 
function func() { 
console.log(this); 
//Window {top: Window, window: Window, location: Location,…} 
console.log(this. isAccess); //true 
Page 6 
} func();
Page 7 
함수내에서 this 는 어디를 가리키는가 ? 
2. 생성자로 생성 후 호출했을 경우 – 생성된 객체를 가르킨다 . 
fun를ct io가n르 F킨un다c(.num1, num2) { 
this.num1 = num1; 
this.num2 = num2; 
} 
Func.prototype.add = function () { 
console.log(this); 
//Func {num1: 1, num2: 2, add: function} 
//Func {num1: 3, num2: 4, add: function} 
console.log(this.num1 + this.num2); 
//3 
//7 
} 
var func1 = new Func(1, 2); 
func1.add(); 
var func2 = new Func(3, 4); 
func2.add();
Page 8 
함수내에서 this 는 어디를 가리키는가 ? 
3. 메서드에 생성 후 호출 – 메서드가 속하는 객체를 가르킨다. 
var caculator1 = { 
num1: 1, 
num2: 2, 
add : function () { 
console.log(this);//Object {num1: 1, num2: 2, add: function} 
console.log(this.num1 + this.num2);//3 
} 
}; 
caculator1 .add(); 
var caculator2 = { 
num1: 3, 
num2: 4, 
add : function () { 
console.log(this); //Object {num1: 3, num2: 4, add: function} 
console.log(this.num1 + this.num2);//7 
} 
}; 
caculator2.add();
Page 9 
함수내에서 this 는 어디를 가리키는가 ? 
4. apply(call) 호출 – 선택한 객체 (null 이나 undefined 이면 전역객체 ) 를 
가르킨다. 
function add(num1, num2) { 
console.log(this) 
//Object{} 
//Window {top: Window, window: Window, location: Location…} 
console.log(num1 + num2); 
//3 
//3 
} 
var caculator1 = {}; 
add.apply(caculator1, [1,2]); 
add.call(null, 1,2);
Page 10 
함수내에서 this 는 어디를 가리키는가 ? 
5. 예외사항 – 메소드에서 생성할 때 다시 내부함수를 정의하고 호출하면 
window 객체를 가르킨다 . 
var caculator1 = { 
num1: 1, 
num2: 2, 
multi: function () { 
var subMulti = function () { 
console.log(this); 
//Window {top: Window, window: Window, location: Location…} 
// 이건 명백히 설계상의 실수라고 할 수 있습니다 . - 더글라스 크락 
포드 
console.log(this.num1 + this.num2);//NaN 
} 
subMulti(); 
} 
}; 
caculator1.multi();
Page 11 
파라미터와 아규먼트 개수가 달라도 호출 ? 
함수 호출시 정의된 파라미터와 아규먼트의 개수가 일치하지 않아도 정상적 
으로 호출이 가능하다 . 
function checkArgCount(num1, num2) { 
var arg = new Array(); 
console.log("num1 : " + num1 + ", num2 : " + num2); 
for (var i =0; i < arguments.length; i++) { 
//arguments -> 배열은 아니지만 배열처럼 꺼내 올 수 있음. 
arg[i] = arguments[i]; 
} 
console.log("arguments : " + arg .join(", ")); 
} 
checkArgCount(1,2);//num1 : 1, num2 : 2, arguments : 1,2 
checkArgCount(1);//num1 : 1, num2 : undefined , arguments : 1 
checkArgCount(1,2,3);//num1 : 1, num2 : 2, arguments : 1,2,3 
arguments : The arguments object is a local variable available 
within all functions
Page 12 
함수내의 유효범위 
변수 : 선언이 어디 되어 있든 접근 가능하나 값을 할당되어 있지 않음 
내부함수 : 선언이 어디 되어 있든 상관없이 함수 내에서 유효함 
function func() { 
console.log(num1 );//undefined - 변수가 아래에 선언 되어 있어도 끌어올리기(hoisting) 가 되서 에러가 나 
지 않고 값이 할당되지 않았다는 undefined 가 출력됨. 
var num1 = 1; 
console.log(num1 );//1 
var num2 = 2; 
add(num1, num2);//add : 3 - 함수가 아래에 선언 되어 있어도 끌어올리기(hoisting) 가 되서 호출 뿐 아니 
라 실행도 된다. 
function add(num1, num2) { 
console.log("add : " + num1 ); 
} 
if (true) { 
var num3 = 3; 
var num4 = 4; 
} 
console.log(num3 );//3 - 접근 가능(java 와 같은 언어였다면 접근 불가능) 
} func();
A closure—unlike a plain function pointer—allows a 
function to access those non-local variables even when 
invoked outside its immediate lexical scope. - 
http://en.wikipedia.org/wiki/Closure_(computer_programming) 
즉시 어휘 범위 밖에서 호출해도 함수 
가 그 지역 변수가 아닌 변수에 액세스 
할 수 있다 . 
Page 13 
클로저 (Closure)?
함수내에 정의된 변수는 내부 함수의 지역변수가 아닌 외부 변수이지만 
참조하고 변경도 가능하다. 
Page 14 
클로저 (Closure)? 
function outerFuction() { 
var isAccess = true; 
console.log(isAccess);//true 
function innnerFunction() { 
console.log(isAccess);//true 
isAccess = false; 
console.log(isAccess );//false 
} 
innnerFunction(); 
console.log(isAccess); //false 
} 
outerFuction();
Page 15 
클로저 (Closure) 는 어떻게 사용하지 ? 
자바스크립트에는 없는 개념인 private 함수 만들기 
function person() { 
var age = 0; 
function checkAdultAge() {//private 함수 
if (age >= 19) { 
return true; 
} 
return false; 
} 
return { 
login : function(name, myAge) { 
age = myAge; 
if (checkAdultAge ()) { 
console.log("로그인성공"); 
} else { 
console.log("미성년자는 로그인할 수 없습니다."); 
} 
} 
} 
} 
console.log(person().login("anne", "18")); // 미성년자는 로그인할 수 없습니다.
Page 16 
클로저 (Closure) 는 어떻게 사용하지 ? 
콜백함수에서 상위 함수의 변수를 접근할때 
function showConsoleMessage(callback) { 
callback(); 
} function showMessage(message) { 
var myMessage = "myMessage : "; 
return showConsoleMessage(function() { 
console.log(myMessage + message );//myMessage : 
show me the message 
}); 
} 
showMessage("show me the message");
Page 17 
클로저 (Closure) 는 흔히 하는 실수 
변수를 참조하는 것이므로 최종 변경된 값이 반영됨 
for(var i = 0; i < 10; i++) { 
setTimeout(function(){ 
console.log(i); //10 만 찍힘 
}, 1000); 
} 
for(var i = 0; i < 10; i++) { 
(function (i) { 
setTimeout(function(){ 
console.log(i);//0~9가 차례로 찍힘 
}, 1000); 
})(i)//즉시 실행 하는 함수를 생성하여 파라미터로 i를 넘김 
}
Each object has an internal link to another object called its 
prototype. https://developer.mozilla.org/en- 
US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain 
각 객체에는 다른 객체를 연결하는 내 
부 링크를 프로토타입이라고 한다 . 
Page 18 
Prototype 이란 ?
Page 19 
Prototype 이란 ? 
예시 
function Person(name) { 
this. name = name; 
} 
Person.prototype.getName = function () { 
console.log(this.name); 
console.log(this); 
} 
var person = new Person("anne"); 
person.getName();
Page 20 
Prototype 이란 ? 
우선순위 – 동일한 이름의 내부 프로퍼티가 선언되어 있을 경우 
우선순위가 높다 
function Person(name) { 
this. name = name; 
this.getName = function () { // 이 프로퍼티가 호출된다 . – 원래 인스턴스 마다 생성 
되기 때문에 올바른 방법이 아니다 . 
console.log(this); 
console.log("this.getName : " + this.name); // this.getName : 
anne 
}; 
} 
Person.prototype.getName = function () { 
console.log(this); 
console.log ("prototype.getName : " + this.name); 
} 
var person = new Person("anne"); 
person.getName();
Page 21 
Prototype 이란 ? 
Prototype 을 이용하면 상속이 가능하다 . 
function Student(score) { 
this. score = score; 
} 
Student.prototype = new Person("anne"); 
Student.prototype.getScore = function () { 
console.log(this. score); 
console.log(this); 
} 
var student = new Student(100); 
student.getScore();

More Related Content

PPTX
골때리는 자바스크립트 발표자료
욱진 양
 
PPTX
Startup JavaScript 8 - NPM, Express.JS
Circulus
 
PPTX
프론트엔드스터디 E05 js closure oop
Young-Beom Rhee
 
PDF
비전공자의 자바스크립트 도전기
jeong seok yang
 
PPTX
ECMAScript 6의 새로운 것들!
WooYoung Cho
 
PDF
Javascript 교육자료 pdf
Hyosang Hong
 
PPTX
Javascript 실행 가능한 코드(Executable Code)와 실행 콘텍스트(Execution Context), Lexical En...
Young-Beom Rhee
 
PPTX
프론트엔드스터디 E04 js function
Young-Beom Rhee
 
골때리는 자바스크립트 발표자료
욱진 양
 
Startup JavaScript 8 - NPM, Express.JS
Circulus
 
프론트엔드스터디 E05 js closure oop
Young-Beom Rhee
 
비전공자의 자바스크립트 도전기
jeong seok yang
 
ECMAScript 6의 새로운 것들!
WooYoung Cho
 
Javascript 교육자료 pdf
Hyosang Hong
 
Javascript 실행 가능한 코드(Executable Code)와 실행 콘텍스트(Execution Context), Lexical En...
Young-Beom Rhee
 
프론트엔드스터디 E04 js function
Young-Beom Rhee
 

What's hot (20)

PPTX
Javascript 함수(function) 개념, 호출패턴, this, prototype, scope
Young-Beom Rhee
 
PPTX
0.javascript기본(~3일차내)
Sung-hoon Ma
 
PPTX
Angular2 가기전 Type script소개
Dong Jun Kwon
 
DOCX
Javascript 완벽 가이드 정리
ETRIBE_STG
 
PPTX
자바스크립트 기초문법~함수기초
진수 정
 
PDF
1.Startup JavaScript - 프로그래밍 기초
Circulus
 
PPTX
프론트엔드스터디 E03 - Javascript intro.
Young-Beom Rhee
 
PDF
Javascript
Hong Hyo Sang
 
PDF
Javascript 조금 더 잘 알기
jongho jeong
 
PPTX
Nodejs, PhantomJS, casperJs, YSlow, expressjs
기동 이
 
PPTX
Angular2 router&http
Dong Jun Kwon
 
PDF
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive
NAVER D2
 
PDF
Ji 개발 리뷰 (신림프로그래머)
beom kyun choi
 
PPTX
Jdk(java) 7 - 5. invoke-dynamic
knight1128
 
PPTX
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
Young-Beom Rhee
 
PDF
안드로이드 개발자를 위한 스위프트
병한 유
 
PDF
[1B4]안드로이드 동시성_프로그래밍
NAVER D2
 
PPTX
[하코사 세미나] 비전공자의 자바스크립트 도전기
인권 김
 
PDF
일단 시작하는 코틀린
Park JoongSoo
 
PPTX
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
Jaeseung Ha
 
Javascript 함수(function) 개념, 호출패턴, this, prototype, scope
Young-Beom Rhee
 
0.javascript기본(~3일차내)
Sung-hoon Ma
 
Angular2 가기전 Type script소개
Dong Jun Kwon
 
Javascript 완벽 가이드 정리
ETRIBE_STG
 
자바스크립트 기초문법~함수기초
진수 정
 
1.Startup JavaScript - 프로그래밍 기초
Circulus
 
프론트엔드스터디 E03 - Javascript intro.
Young-Beom Rhee
 
Javascript
Hong Hyo Sang
 
Javascript 조금 더 잘 알기
jongho jeong
 
Nodejs, PhantomJS, casperJs, YSlow, expressjs
기동 이
 
Angular2 router&http
Dong Jun Kwon
 
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive
NAVER D2
 
Ji 개발 리뷰 (신림프로그래머)
beom kyun choi
 
Jdk(java) 7 - 5. invoke-dynamic
knight1128
 
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
Young-Beom Rhee
 
안드로이드 개발자를 위한 스위프트
병한 유
 
[1B4]안드로이드 동시성_프로그래밍
NAVER D2
 
[하코사 세미나] 비전공자의 자바스크립트 도전기
인권 김
 
일단 시작하는 코틀린
Park JoongSoo
 
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
Jaeseung Ha
 
Ad

Viewers also liked (13)

PPTX
퍼블리셔, 디자인을 퍼블리싱하다
jeong seok yang
 
PPTX
클로저 1
samagu0030
 
PDF
시나브로 CSS3
승환 오
 
PDF
CSS3 천기누설
Toby Yun
 
PPTX
처음부터 다시 배우는 HTML5 & CSS3 강의자료 7일차
Michael Yang
 
PPTX
처음부터 다시 배우는 HTML5 & CSS3 강의자료3일차
Michael Yang
 
PPTX
처음부터 다시 배우는 HTML5 & CSS3 1일차
Michael Yang
 
PDF
나의 jQuery 실력 향상기
정석 양
 
PDF
Html5 강좌파일_v_3.0
Youngjo Jang
 
PPTX
인내심없는 개발자를 위한 자바스크립트 - 한줄씩 영어공부하기.
Nasol Kim
 
PPTX
처음부터 다시 배우는 HTML5 & CSS3 강의자료 2일차
Michael Yang
 
PPTX
프론트엔드 개발자의 자바스크립트
jeong seok yang
 
PDF
Top 10 Questions about HTML5
Jonathan Jeon
 
퍼블리셔, 디자인을 퍼블리싱하다
jeong seok yang
 
클로저 1
samagu0030
 
시나브로 CSS3
승환 오
 
CSS3 천기누설
Toby Yun
 
처음부터 다시 배우는 HTML5 & CSS3 강의자료 7일차
Michael Yang
 
처음부터 다시 배우는 HTML5 & CSS3 강의자료3일차
Michael Yang
 
처음부터 다시 배우는 HTML5 & CSS3 1일차
Michael Yang
 
나의 jQuery 실력 향상기
정석 양
 
Html5 강좌파일_v_3.0
Youngjo Jang
 
인내심없는 개발자를 위한 자바스크립트 - 한줄씩 영어공부하기.
Nasol Kim
 
처음부터 다시 배우는 HTML5 & CSS3 강의자료 2일차
Michael Yang
 
프론트엔드 개발자의 자바스크립트
jeong seok yang
 
Top 10 Questions about HTML5
Jonathan Jeon
 
Ad

Similar to 헷갈리는 자바스크립트 정리 (20)

PPTX
Startup JavaScript 6 - 함수, 스코프, 클로저
Circulus
 
PPTX
Java script의 이해
seungkyu park
 
PDF
Javascript 101
Sungwoo Choo
 
PDF
외계어 스터디 3/5 function and object
민태 김
 
PPTX
자바스크립트 함수
유진 변
 
PDF
EcmaScript6(2015) Overview
yongwoo Jeon
 
PPTX
Clojure programming-김민지
ETRIBE_STG
 
PDF
Start IoT with JavaScript - 6.함수
Park Jonggun
 
PDF
Es2015 Simple Overview
Kim Hunmin
 
PPTX
Javascript
Joshua Yoon
 
PPT
Java script
영남 허
 
PDF
JS특징(scope,this,closure)
지수 윤
 
PDF
Javascript Closure
지수 윤
 
PPTX
JavaScript Fundermetal
Kwangho SEO
 
PPTX
Startup JavaScript 4 - 객체
Circulus
 
PPTX
자바스크립트 패턴 3장
Software in Life
 
PDF
JavaScript Patterns - Chapter 3. Literals and Constructors
Hyuncheol Jeon
 
PDF
Javascript - Function
wonmin lee
 
PPTX
javascript03
ChangHyeon Bae
 
PDF
ES6 for Node.js Study 5주차
승빈이네 공작소
 
Startup JavaScript 6 - 함수, 스코프, 클로저
Circulus
 
Java script의 이해
seungkyu park
 
Javascript 101
Sungwoo Choo
 
외계어 스터디 3/5 function and object
민태 김
 
자바스크립트 함수
유진 변
 
EcmaScript6(2015) Overview
yongwoo Jeon
 
Clojure programming-김민지
ETRIBE_STG
 
Start IoT with JavaScript - 6.함수
Park Jonggun
 
Es2015 Simple Overview
Kim Hunmin
 
Javascript
Joshua Yoon
 
Java script
영남 허
 
JS특징(scope,this,closure)
지수 윤
 
Javascript Closure
지수 윤
 
JavaScript Fundermetal
Kwangho SEO
 
Startup JavaScript 4 - 객체
Circulus
 
자바스크립트 패턴 3장
Software in Life
 
JavaScript Patterns - Chapter 3. Literals and Constructors
Hyuncheol Jeon
 
Javascript - Function
wonmin lee
 
javascript03
ChangHyeon Bae
 
ES6 for Node.js Study 5주차
승빈이네 공작소
 

헷갈리는 자바스크립트 정리

  • 2. Page 2 목차 자바스크립트 함수란 ? 함수 내의 this 와 유효범위는 ? Closure 란 ? Prototype 이란 ?
  • 3. 자바스크립트 함수는 first-class object 이다 ? first-class object : An entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. - http://en.wiktionary.org/wiki/first-class_ Page 3 object 자바스크립트 함수 == first-class Object 위의 세 가지 방법을 함수로 할 수 있다 !
  • 4. 자바스크립트 함수는 first-class object 이다 ? Page 4 1. passed as a parameter function func(callback ) { callback(); }; func(function () { console.log("I am function"); } ); 2. returned from a subroutine function func() { return function () { console.log("I am function"); } }; func()(); 3. assigned into a variable var func = function () { console.log("I am function"); } func();
  • 5. Inside a function, the value of this depends on how the function is called. -https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Operators/this 함수가 어떻게 호출되느냐에 따라 달 라진다 ! Page 5 함수내에서 this 는 어디를 가리키는가 ?
  • 6. 함수내에서 this 는 어디를 가리키는가 ? 1. 함수 생성 후 호출하였을 경우 – 전역 객체 (window) 를 가르킨다. var isAccess = true; function func() { console.log(this); //Window {top: Window, window: Window, location: Location,…} console.log(this. isAccess); //true Page 6 } func();
  • 7. Page 7 함수내에서 this 는 어디를 가리키는가 ? 2. 생성자로 생성 후 호출했을 경우 – 생성된 객체를 가르킨다 . fun를ct io가n르 F킨un다c(.num1, num2) { this.num1 = num1; this.num2 = num2; } Func.prototype.add = function () { console.log(this); //Func {num1: 1, num2: 2, add: function} //Func {num1: 3, num2: 4, add: function} console.log(this.num1 + this.num2); //3 //7 } var func1 = new Func(1, 2); func1.add(); var func2 = new Func(3, 4); func2.add();
  • 8. Page 8 함수내에서 this 는 어디를 가리키는가 ? 3. 메서드에 생성 후 호출 – 메서드가 속하는 객체를 가르킨다. var caculator1 = { num1: 1, num2: 2, add : function () { console.log(this);//Object {num1: 1, num2: 2, add: function} console.log(this.num1 + this.num2);//3 } }; caculator1 .add(); var caculator2 = { num1: 3, num2: 4, add : function () { console.log(this); //Object {num1: 3, num2: 4, add: function} console.log(this.num1 + this.num2);//7 } }; caculator2.add();
  • 9. Page 9 함수내에서 this 는 어디를 가리키는가 ? 4. apply(call) 호출 – 선택한 객체 (null 이나 undefined 이면 전역객체 ) 를 가르킨다. function add(num1, num2) { console.log(this) //Object{} //Window {top: Window, window: Window, location: Location…} console.log(num1 + num2); //3 //3 } var caculator1 = {}; add.apply(caculator1, [1,2]); add.call(null, 1,2);
  • 10. Page 10 함수내에서 this 는 어디를 가리키는가 ? 5. 예외사항 – 메소드에서 생성할 때 다시 내부함수를 정의하고 호출하면 window 객체를 가르킨다 . var caculator1 = { num1: 1, num2: 2, multi: function () { var subMulti = function () { console.log(this); //Window {top: Window, window: Window, location: Location…} // 이건 명백히 설계상의 실수라고 할 수 있습니다 . - 더글라스 크락 포드 console.log(this.num1 + this.num2);//NaN } subMulti(); } }; caculator1.multi();
  • 11. Page 11 파라미터와 아규먼트 개수가 달라도 호출 ? 함수 호출시 정의된 파라미터와 아규먼트의 개수가 일치하지 않아도 정상적 으로 호출이 가능하다 . function checkArgCount(num1, num2) { var arg = new Array(); console.log("num1 : " + num1 + ", num2 : " + num2); for (var i =0; i < arguments.length; i++) { //arguments -> 배열은 아니지만 배열처럼 꺼내 올 수 있음. arg[i] = arguments[i]; } console.log("arguments : " + arg .join(", ")); } checkArgCount(1,2);//num1 : 1, num2 : 2, arguments : 1,2 checkArgCount(1);//num1 : 1, num2 : undefined , arguments : 1 checkArgCount(1,2,3);//num1 : 1, num2 : 2, arguments : 1,2,3 arguments : The arguments object is a local variable available within all functions
  • 12. Page 12 함수내의 유효범위 변수 : 선언이 어디 되어 있든 접근 가능하나 값을 할당되어 있지 않음 내부함수 : 선언이 어디 되어 있든 상관없이 함수 내에서 유효함 function func() { console.log(num1 );//undefined - 변수가 아래에 선언 되어 있어도 끌어올리기(hoisting) 가 되서 에러가 나 지 않고 값이 할당되지 않았다는 undefined 가 출력됨. var num1 = 1; console.log(num1 );//1 var num2 = 2; add(num1, num2);//add : 3 - 함수가 아래에 선언 되어 있어도 끌어올리기(hoisting) 가 되서 호출 뿐 아니 라 실행도 된다. function add(num1, num2) { console.log("add : " + num1 ); } if (true) { var num3 = 3; var num4 = 4; } console.log(num3 );//3 - 접근 가능(java 와 같은 언어였다면 접근 불가능) } func();
  • 13. A closure—unlike a plain function pointer—allows a function to access those non-local variables even when invoked outside its immediate lexical scope. - http://en.wikipedia.org/wiki/Closure_(computer_programming) 즉시 어휘 범위 밖에서 호출해도 함수 가 그 지역 변수가 아닌 변수에 액세스 할 수 있다 . Page 13 클로저 (Closure)?
  • 14. 함수내에 정의된 변수는 내부 함수의 지역변수가 아닌 외부 변수이지만 참조하고 변경도 가능하다. Page 14 클로저 (Closure)? function outerFuction() { var isAccess = true; console.log(isAccess);//true function innnerFunction() { console.log(isAccess);//true isAccess = false; console.log(isAccess );//false } innnerFunction(); console.log(isAccess); //false } outerFuction();
  • 15. Page 15 클로저 (Closure) 는 어떻게 사용하지 ? 자바스크립트에는 없는 개념인 private 함수 만들기 function person() { var age = 0; function checkAdultAge() {//private 함수 if (age >= 19) { return true; } return false; } return { login : function(name, myAge) { age = myAge; if (checkAdultAge ()) { console.log("로그인성공"); } else { console.log("미성년자는 로그인할 수 없습니다."); } } } } console.log(person().login("anne", "18")); // 미성년자는 로그인할 수 없습니다.
  • 16. Page 16 클로저 (Closure) 는 어떻게 사용하지 ? 콜백함수에서 상위 함수의 변수를 접근할때 function showConsoleMessage(callback) { callback(); } function showMessage(message) { var myMessage = "myMessage : "; return showConsoleMessage(function() { console.log(myMessage + message );//myMessage : show me the message }); } showMessage("show me the message");
  • 17. Page 17 클로저 (Closure) 는 흔히 하는 실수 변수를 참조하는 것이므로 최종 변경된 값이 반영됨 for(var i = 0; i < 10; i++) { setTimeout(function(){ console.log(i); //10 만 찍힘 }, 1000); } for(var i = 0; i < 10; i++) { (function (i) { setTimeout(function(){ console.log(i);//0~9가 차례로 찍힘 }, 1000); })(i)//즉시 실행 하는 함수를 생성하여 파라미터로 i를 넘김 }
  • 18. Each object has an internal link to another object called its prototype. https://developer.mozilla.org/en- US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain 각 객체에는 다른 객체를 연결하는 내 부 링크를 프로토타입이라고 한다 . Page 18 Prototype 이란 ?
  • 19. Page 19 Prototype 이란 ? 예시 function Person(name) { this. name = name; } Person.prototype.getName = function () { console.log(this.name); console.log(this); } var person = new Person("anne"); person.getName();
  • 20. Page 20 Prototype 이란 ? 우선순위 – 동일한 이름의 내부 프로퍼티가 선언되어 있을 경우 우선순위가 높다 function Person(name) { this. name = name; this.getName = function () { // 이 프로퍼티가 호출된다 . – 원래 인스턴스 마다 생성 되기 때문에 올바른 방법이 아니다 . console.log(this); console.log("this.getName : " + this.name); // this.getName : anne }; } Person.prototype.getName = function () { console.log(this); console.log ("prototype.getName : " + this.name); } var person = new Person("anne"); person.getName();
  • 21. Page 21 Prototype 이란 ? Prototype 을 이용하면 상속이 가능하다 . function Student(score) { this. score = score; } Student.prototype = new Person("anne"); Student.prototype.getScore = function () { console.log(this. score); console.log(this); } var student = new Student(100); student.getScore();