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();