Jisu kim java script study 02

27
JavaScript 2일차 2.1 Function

Transcript of Jisu kim java script study 02

JavaScript 2일차

2.1 Function

Function 선언

function add(lv, rv) {

return lv + rv;

}

Function 표현식

// 익명(Lambda)함수

var foo = function (a, b) {return a + b;};

foo(10, 1); // 11

// 재귀하고 싶을땐 이름을 붙여줄 수 있음.

var bar = function fac(a, b) {return n<2 ? 1 : n * fac(n-1);};

전역변수 참조하기(this 키워드)

var a = 10;

function foo() {

var a = 1; // a가 local변수로 있다면

console.log(a); // 1

console.log(this.a); // 10

}

foo();

● this는 현재 Context 객체를 반환– Function에서는 소유자, Class에서는 자기자신

Call by Value

● ex1)

var b = 1;

function foo(a) {

a = 10;

}

foo(b);

console.log(b); // 1

Call by Value

하지만 Object를 넘겨주면 Call by Reference?● ex2)

var b = {foo : 1, bar : 2};

function foo(a) {

a.foo = 10;

}

foo(b);

console.log(b.foo); // 10

Call by Value

No, Object의 값자체를 수정하면 적용 안됨

● ex3)

var b = {foo : 1, bar : 2};

function foo(a) {

a = {foo : 10, bar : 2};

}

foo(b);

console.log(b.foo); // 1

● Object나 function을 받을땐 내부 Context에 접근할수 있는

참조변수(C언어의 포인터와 비슷)가 복사됨

가변인자 Function

● 받은 인자들은 arguments배열로 저장된다.– ex)

function sumAll() {

var sum=0;

for(var i in arguments) {

sum += arguments[i];

}

return sum;

}

sumAll(1, 2, 3, 4); // 10

JavaScript 2일차

2.2 객체지향

객체지향● JavaScript는 객체지향 언어지만 Prototype-Base

언어라서 Class가 존재하지 않음.

● 따라서 Function의 새 인스턴스를 생성하는 방식으로 객체지향 설계 가능.

● Prototype-Base Programming

객체지향 - 새 인스턴스 만들기(new 키워드)

● ex)

function Person() {

this.a = 'hello';

console.log('Person Create');

}

var person1 = new Person();

var person2 = new Person();

console.log(person1.a); // hello

객체지향 – Private Method

● ex1)

function Person1() {

var foo = function()

{ console.log('hello');};

};

var person1 = new Person1();

person1.foo(); // error!

객체지향 – Public Method(this 사용)

● ex2)

function Person1() {

var foo = function()

{ console.log('hello');};

this.bar = function() { foo(); };

};

var person1 = new Person1();

person1.bar(); // hello

객체지향 – Static Method(prototype 사용)

● ex3)

function Person2() {};

Person2.prototype.foo = function()

{

console.log('hello');};

var person2 = new Person2();

person2.foo(); // hello

차이점?

● function내부에서 추가하면

instance에 복사됨

● prototype에 추가하면 instance 내부 property를

먼저 탐색하여 실행하고 없을 경우

__proto__에서 탐색하여 실행함.

● __proto__은 Function의 prototype의 참조변수임. ↓

Property 탐색 순서

instance의 body →

instance의 __proto__ →

__proto__내부의 __proto__가 undefine일 때 까지 반복...

정보은닉

● Private 변수를 만들어주고 getter setter구현

ex)

function Person() {var a = 'hello';

this.getA = function(){return a;}

this.setA = function(value){a = value;}

};

var person = new Person();

console.log(person.getA()); // hello

person.setA('bye');

console.log(person.getA()); // bye

console.log(person.a); // undefined

상속

● prototype을 이용하면 상속을 구현할수 있다.

ex)

function Person() {var a = 'hello';

console.log('Person');

this.getA = function(){return a;}

this.setA = function(value){a = value;}

};

function Student() {var b = 'Student';

console.log('Student');

this.getB = function(){return b;}

this.setB = function(value){b = value;}

Person.call(this); // Person생성자 호출

};

Student.prototype = new Person(); // Person상속

///////////////////////////// 사용 /////////////////////////////

var student = new Student();

console.log(student.getA());

console.log(student.getB());

JavaScript 2일차

2.3 Closure

클로저(Closure)란?

● 먼저 다음의 코드를 살펴보자.

function one(){

var a = 'hello';

return function(){

console.log(a);

}

}

two = one();

two(); // hello

클로저(Closure)란?

일반적으로 생각했을때, one()은 작업이 끝났으니 소멸되어서

two()를 호출하였을 때는 one의 a변수에 접근할수 없어야 한다.

하지만, two()에선 정상적으로 one의 a를 참조했다.

함수를 반환하였을 때, 인스턴스가 생성되고 참조변수를 반환하여 해제되기 전까지 instance는 해제되지 않기 때문이다.

이러한 특성을 클로저(Closure)라고 한다.

클로저의 이해

function myclass()

{

var func;

this.setfunc = function (f)

{

func = f;

};

this.exefunc = function ()

{

func();

};

}

var cls1 = new myclass;

var cls2 = new myclass;

var i = 1;

cls1.setfunc(function(){console.log(i)});

++i;

cls2.setfunc(function(){console.log(i)});

cls1.exefunc();

cls2.exefunc();

클로저의 이해

22

가 출력됨..

이유?

● 클로저때문에 나타나는 현상이다.

● i변수를 cls1과 cls2가 참조하고 있기 때문

해결방법

● 함수로 한번 더 감싸서 복사된 i를 참조하도록 한다.

클로저의 이해

var cls1 = new myclass;

var cls2 = new myclass;

var i = 1;

(function(ii){cls1.setfunc(function(){console.log(ii)})})(i)

++i;

(function(ii){cls2.setfunc(function(){console.log(ii)})})(i)

cls1.exefunc();

cls2.exefunc();

질문받음