21
Page 1 헷헷헷헷 헷헷헷헷헷헷 헷헷 by 이이이

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

  • Upload
    -

  • View
    2.086

  • Download
    5

Embed Size (px)

DESCRIPTION

공부겸 정리

Citation preview

Page 1: 헷갈리는 자바스크립트 정리

Page 1

헷갈리는 자바스크립트 정리by 이은숙

Page 2: 헷갈리는 자바스크립트 정리

Page 2

목차

자바스크립트 함수란 ?

함수 내의 this와 유효범위는 ?

Closure란 ?

Prototype이란 ?

Page 3: 헷갈리는 자바스크립트 정리

Page 3

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_object

자바스크립트 함수 == first-class Object위의 세 가지 방법을 함수로 할 수 있다 !

자바스크립트 함수는 first-class object이다 ?

Page 4: 헷갈리는 자바스크립트 정리

Page 4

function func(callback) { callback();};func(function () { console.log("I am function"); });

1. passed as a parameter

function func() { return function () { console.log("I am function"); }};func()();

2. returned from a subroutine

var func = function () { console.log("I am function"); }func();

3. assigned into a variable

자바스크립트 함수는 first-class object이다 ?

Page 5: 헷갈리는 자바스크립트 정리

Page 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

함수가 어떻게 호출되느냐에 따라 달라진다 !

함수내에서 this는 어디를 가리키는가 ?

Page 6: 헷갈리는 자바스크립트 정리

Page 6

1. 함수 생성 후 호출하였을 경우 – 전역 객체 (window)를 가르킨다 .

var isAccess  = true;function func() { console.log(this); //Window {top: Window, window: Window, location: Location,…} console.log(this. isAccess); //true}func();

함수내에서 this는 어디를 가리키는가 ?

Page 7: 헷갈리는 자바스크립트 정리

Page 7

2. 생성자로 생성 후 호출했을 경우 – 생성된 객체를 가르킨다 .를 가르킨다 .function Func(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();

함수내에서 this는 어디를 가리키는가 ?

Page 8: 헷갈리는 자바스크립트 정리

Page 8

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

함수내에서 this는 어디를 가리키는가 ?

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

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

Page 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,2checkArgCount(1);//num1 : 1, num2 : undefined , arguments : 1checkArgCount(1,2,3);//num1 : 1, num2 : 2, arguments : 1,2,3arguments : The arguments object is a local variable available

within all functions

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

Page 13: 헷갈리는 자바스크립트 정리

Page 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)

즉시 어휘 범위 밖에서 호출해도 함수가 그 지역 변수가 아닌 변수에 액세스 할 수 있다 .

클로저 (Closure)?

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

함수내에 정의된 변수는 내부 함수의 지역변수가 아닌 외부 변수이지만 참조하고 변경도 가능하다 .

Page 15: 헷갈리는 자바스크립트 정리

Page 15

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")); // 미성년자는 로그인할 수 없습니다 .

자바스크립트에는 없는 개념인 private 함수 만들기

클로저 (Closure)는 어떻게 사용하지 ?

Page 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");

콜백함수에서 상위 함수의 변수를 접근할때

Page 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 를 넘김}

변수를 참조하는 것이므로 최종 변경된 값이 반영됨

Page 18: 헷갈리는 자바스크립트 정리

Page 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

각 객체에는 다른 객체를 연결하는 내부 링크를 프로토타입이라고 한다 .

Prototype이란 ?

Page 19: 헷갈리는 자바스크립트 정리

Page 19

function Person(name) { this. name = name;}Person.prototype.getName = function () { console.log(this.name); console.log(this);}var person = new Person("anne"); person.getName();

예시

Prototype이란 ?

Page 20: 헷갈리는 자바스크립트 정리

Page 20

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

우선순위 – 동일한 이름의 내부 프로퍼티가 선언되어 있을 경우 우선순위가 높다

Prototype이란 ?

Page 21: 헷갈리는 자바스크립트 정리

Page 21

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

Prototype을 이용하면 상속이 가능하다 .