Javascript

MVC패턴, 화살표 함수, 전역객체, 디스트럭처링, ISO, 클로저 함수란

Antonio Bae 2023. 7. 17. 15:36

MVC 패턴이란?

MVC란 Model-View-Controller의 약자로 애플리케이션을 세 가지 역할로 구분한 개발 방법론입니다.

 

위의 개념을 WEB에 적용 시

  1. 사용자가 웹사이트에 접속 (Users)
  2. Controller는 사용자가 요청한 웹페이지를 서비스하기 위해서 모델을 호출 (Manipulates)
  3. Model은 데이터베이스나 파일과 같은 데이터 소스를 제어한 후 그 결과를 Return
  4. ControllerModel이 리턴한 결과를 View에 반영 (Updates)
  5. 데이터가 반영된 View는 사용자에게 보여짐 (Sees)

모델: 데이터를 가진 객체를 모델이라고 지칭합니다. 데이터는 내부의 상태에 대한 정보를 가질 수도 있고, 모델을 표현하는 이름 속성으로 가질 수 있습니다. 모델의 상태에 변화가 있을 때 컨트롤러와 뷰에 이를 통보합니다. 이와 같은 통보를 통해 뷰는 최신의 결과를 보여줄 수 있고, 컨트롤러는 모델의 변화에 따른 적용 가능한 명령을 추가, 제거, 수정할 수 있습니다.

 

전역객체, THIS ?

전역객체(Global object)는 특수한 객체다. 모든 객체는 이 전역객체의 프로퍼티다.

...rest

ex)고등학고때 영어점수

 

function myF(name, ages, ...jumSoo) { ~~~~~~~~~}

myF(name, ages, myHighSchoolEnglishValue);

 

function myF(...jumSoo) { ~~~~~~~~~}

myF(myHighSchoolEnglishValue);

 

 

javascript는 객체가 두가지 의미가 있음

let myO = {“zard”:90, “stormy”:20} -유일한 객체

function Aobj() {this.~~~} -복제 가능

function ===1. 함수 ------ 함수(return 쫀대)

+---- 프로시져(procedure) return 없음

====> Arrow Function() => {~~~~~~}

2. 객체(class)

=====> Class 문법 적용(우리가 배워야 할 것)

중괄호: 객체를 가르킴

() ---->콜을 해야 함수가 실행이 됨

 

var o = {'func':function(){alert('Hello?');}

}

o[‘func’]; ===>o.func

o[‘func’](); ===>o.func()

 

context = ‘맥락’

this = 연결점

window = 최상위객체

 

객체 안의 this는 자기자신을 가르키나 100%는 아님

 

관습

let myS = “”; // 문자 담을게

let myV = 0; // 숫자 담을게

let myO = null; //객체 담을게

 

 

 

 

MVC패턴 도입 → REACT(최근 네이버 도입)

Model, View, Controller의 약자

애플리케이션을 세 가지 역할로 구분한 개발 방법론

 

 

 

디스트럭쳐링 : 일일히 탐색할 필요없이 원하는 값만 바로 파싱 하는 것

객체 구조를 제거.

1. 객체 디스트럭처링

2. 배열 디스트럭처링

 

var o = {p:42, 1:true};

var {p:foo, q:bar} =o;

 

console.log(foo);

console.log(bar);

 

 

1.화살표 함수 arrow function

function 키워드 대신 간략한 방법으로 함수를 선언하는 방법

자세한 설명은 아래 사이트와 코드를 통해 확인 가능

https://poiemaweb.com/es6-arrow-function

 

Arrow function | PoiemaWeb

Arrow function(화살표 함수)은 function 키워드 대신 화살표(=>)를 사용하여 간략한 방법으로 함수를 선언할 수 있다. 하지만 모든 경우 사용할 수 있는 것은 아니다. 문법은 아래와 같다.

poiemaweb.com

outer를 화살표 함수로 나타낸 식이 outer2 함수이며 둘은 같은 결과를 냅니다.

 

function outer(x){
return function inner(){
return x*x;
}
}
const innerFunc1 = outer(10);
const result1 = innerFunc1();
console.log(result1);

//arrow func
const outer2 = (y) => () => y*y;
const innerFunc2 = outer2(10);
const result2 = innerFunc2();
console.log(result2);

또 다른 예시

let sum = (a, b) => a + b;

/* 위 화살표 함수는 아래 함수의 축약 버전입니다.

let sum = function(a, b) {
  return a + b;
};
*/

alert( sum(1, 2) ); // 3
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>this ES6</title>
</head>

<body>
<script>
// function MyO() {
// this.age = ~~~
// this.name =
// this.PrintAnswer = function () { document.write("Antonio"); }
// }

// let my001 = new MyO();
// let my002 = new MyO();

// 객체 안의 this는 자기자신을 가르키나 100%는 아님
function func() {
if (window === this) {
document.write("window === this");
}
}
func();
document.write("<br>");

var o = {
func: function () {
if (o === this) {
document.write("o === this");
}
}
}
o.func();

//생성자의 호출
//아래 코드는 함수를 호출했을 때와 new를 이용해서 생성자를 호출했을 때의 차이를 보여준다.
var funcThis = null;

function Func() {
funcThis = this;
}
var o1 = Func();
if (funcThis === window) {
document.write('window');
}

var o2 = new Func();
if (funcThis === o2) {
document.write('o2');
}
// 생성자는 빈 객체를 만든다. 그리고 이 객체내에서 this는 만들어진 객체를 가르킨다. 이것은 매우 중요한 사실이다. 생성자가 실행되기 전까지는 객체는 변수에도 할당될 수 없기 때문에 this가 아니면 객체에 대한 어떠한 작업을 할 수 없기 때문이다.

//템플릿 리터럴
function Func(){
document.write(o);
}
var o = new Func();

const template = `템플릿 리터럴은 '작은따옴표'와 큰따옴표를 혼용할 수 있다.`;
console.log(template);

const first = 'ung-mo';
const last = 'Lee';

console.log('My name is' +first + ' ' + last + '.');
console.log(`My name is ${first} ${last}.`);

//문자열로 강제로 변경 interpolation
console.log(`1+1=${1+1}`);

//화살표함수 arrow function
const pow = x => x*x;
console.log(pow(10)); //100

const arr = [1,2,3];
const pow1 = arr.map(x => x*x);

console.log(pow1);
 
//기본
const str1=["A","B","C"];
let pushVal = (abc) => {str1.push(abc)}
pushVal("D");
console.log(str1);

//기본형
let addNum = (one, two) => {return one +two}
console.log(addNum(1,2)); //3
let addNum2 = (one,two) => one+two;
console.log(addNum2(2,3)); //5

let plusNum = one => ++one;
console.log(plusNum(100)); //101

//매개변수가 없을때는 괄호를 쳐줘
let banjang =() =>{alert("손아영");}
console.log(banjang());

//중괄호일 경우 한덩어리야 라고 알려줘야 함
let obj = (val) => {attr:val}
console.log(obj("hellow")); //undefined
let obj2 = (val) => ({attr:val})
console.log(obj2("world")); //{attr:"world"}

//자기자신 호출

</script>

</body>

</html>

화살표 함수 2

argument yield 키워드 = generator로서 사용불가
arrow 함수는 this를 새로 정의하지 않는다
     this를 선언한 바로 앞 문맥을 이어받는다.

 

inner 와 outer 출력하는 방법이 다르니 직접 실행해볼것

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>arrow_funciton ES6</title>
 
</head>
<body>
<script>
//argument yield 키워드 = generator로서 사용불가
//arrow 함수는 this를 새로 정의하지 않는다
// this를 선언한 바로 앞 문맥을 이어받는다.
(function myF(aaa) {alert(aaa);})("ZARD");
(()=> {alert(2); })(); //즉시실행함수
(aaa => {alert(aaa);})(1004)

let restArray = (a,b, ...rest)=> console.log(a,b,rest);
restArray(1,2,3,4,5);
let defualtValue = (a,b=1) => console.log(a*b);
defualtValue(5);

//엄격모드(use strict)->tyscript로 넘어가고 사장됨
//26p inner
(function() {
this.name = 'outer';
var inner = {
name: 'inner',
getName: function(){
return this.name;
}
};
console.log(inner.getName());
}());

//27p outer
(function() {
this.name = 'outer';
var inner = {
name: 'inner',
getName: ()=>{
return this.name;
}
};
console.log(inner.getName());
}());
 
//28p addEventListener 에서 사용시 유의!
// fButton.addEventListener('click', function(){
// console.log(this===fButton); //true
// console.log(this===window); //false
// });

//Arrow 함수에서 this가 상위 문맥을 가리킨다
// aButton.addEventListener('click',()=>{
// console.log(this===aButton); //false
// console.log(this===window); //true
// });
 
//arrow와 클래스 형태로 적어라
 



</script>
</body>
</html>

 

3.객체 디스트럭쳐링 Destructuring

오늘 강의에서 가장 핵심내용입니다.

 

데이터를 파싱할때 하나하나 값을 찾아다니는 것이 아니라 key value 형태로

원하는 값을 원하는 만큼만 빠르게 갖고오는 방법입니다.

 

이렇게 되면 저번에 강의했던 parsing 개념 설명때처럼 값을 하나하나 검색해서 들어가는 것이 아니라 바로 해당 객체의 내용을 뽑아올 수 있습니다.

 

https://poiemaweb.com/es6-destructuring

 

Destructuring | PoiemaWeb

디스트럭처링(Destructuring)은 구조화된 객체(배열 또는 객체)를 Destructuring(비구조화, 파괴)하여 개별적인 변수에 할당하는 것이다. 배열 또는 객체 리터럴에서 필요한 값만을 추출하여 변수에 할

poiemaweb.com

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>객체 Destructuring</title>
</head>

<body>
<script>
// ES5
var obj = { age: 'Ungmo', blood: 'Lee' };

var age = obj.age;
var blood = obj.blood;

console.log(age, blood); // Ungmo Lee

// ES6 Destructuring
const obj1 = { age : 'Ungmo', blood: 'Lee', height:'176' };

// 프로퍼티 키를 기준으로 디스트럭처링 할당이 이루어진다. 순서와 개수는 의미가 없다.
// 변수 lastName, firstName만 선언되고 obj(initializer(초기화자))가 Destructuring(비구조화, 파괴)되어 할당된다.
const { lastName, firstName } = obj1;

console.log(firstName, lastName); // Ungmo Lee
</script>
</body>

</html>

4.spread 문법 활용

spread 문법을 활용해서 원하는 내용을 리스트 형태로 뽑고 특정 값을 활용하는 방법이 있습니다.

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
<script>
let x, y, z;

[x, y] = [1, 2];
console.log(x, y); // 1 2

[x, y] = [1];
console.log(x, y); // 1 undefined

[x, y] = [1, 2, 3];
console.log(x, y); // 1 2

[x, , z] = [1, 2, 3];
console.log(x, z); // 1 3

// 기본값
[x, y, z = 3] = [1, 2];
console.log(x, y, z); // 1 2 3

[x, y = 10, z = 3] = [1, 2];
console.log(x, y, z); // 1 2 3

[x, ...y] = [1, 2, 3];
console.log(x, y);
 
// spread 문법
[x, ...y] = [1, 2, 3];
console.log(x, y); // 1 [ 2, 3 ]i
</script>
</body>

</html>

 

5.ISO

날짜 포멧 간단 표현방법입니다.

formattedDate 키워드를 활용하여 날짜를 불러온 후에,

toISOString 키워드를 활용하여 문자열 형태로 값을 출력하는 방법입니다.

그리고 split을 활용하여 데이터를 나누고 원하는 값을 갖고 올 수 있습니다.

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ISO</title>
</head>

<body>
<script>
const today = new Date(); // Tue May 21 2019 22:19:42 GMT+0900 (한국 표준시)
const formattedDate = today.toISOString().substring(0, 18); // "2019-05-21"
document.write(formattedDate);
const [year, month, day] = formattedDate.split('-');
console.log([year, month, day]); // [ '2019', '05', '21' ]

//숫자 형식으로도 가능
const [a, b, c] = formattedDate.split('-');
console.log([a, b, c]); // [ '2019', '05', '21' ]

 

</script>
</body>

</html>

6.클로저 함수

프로그래머들은 전역변수 설정하는 것을 극도로 싫어합니다.

그래서 함수 안에 변수 설정이 디폴트!!

함수안에 변화된 변수값 설정하는 방법이 클로저 

렉시컬 환경 :특정 코드가 작성, 선언된 환경

정적변수(static)=지역변수: 전역 변수처럼 프로그램이 종료되지 않는 한 메모리가 소멸되지 않고, 특별히 초깃값을 지정하지 않아도 자동으로 0을 가지는 변수, 선언된 함수 내에서만 사용 가능.

https://poiemaweb.com/js-closure

<!DOCTYPE html>
<html lang="KO">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 프로그래머들은 전역변수 설정하는 것을 극도로 싫어함
// 그래서 함수 안에 변수 설정이 디폴트!!
// 함수안에 변화된 변수값 설정하는 방법이 클로저
// 렉시컬 환경 :특정 코드가 작성, 선언된 환경
// 정적변수(static)=지역변수: 전역 변수처럼 프로그램이 종료되지 않는 한 메모리가 소멸되지 않고, 특별히 초깃값을 지정하지 않아도 자동으로 0을 가지는 변수, 선언된 함수 내에서만 사용 가능.
function outerFunc() {
var x = 10;
var innerFunc = function () { console.log(x++); };
return innerFunc;
}

// 함수 outerFunc를 호출하면 내부 함수 innerFunc가 반환된다.
// 그리고 함수 outerFunc의 실행 컨텍스트는 소멸한다.
// outerFunc 함수로 진입한게 아니라 innerFunc로 진입
// 즉, 1회만 초기화되는 변수를 만들어낸것
var inner = outerFunc();
inner(); // 10
inner(); // 10
inner(); // 10
inner(); // 10
inner(); // 10

</script>

</body>

</html>

6.클로저함수2

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button class="toggle">toggle</button>
<div class="box" style="width: 100px; height: 100px; background: red;"></div>
<script>
var box = document.querySelector('.box');
var toggleBtn = document.querySelector('.toggle');

var toggle = (function () {
var isShow = false;

// ① 클로저를 반환
return function () {
box.style.display = isShow ? 'block' : 'none';
// ③ 상태 변경
isShow = !isShow;
};
})();

// ② 이벤트 프로퍼티에 클로저를 할당
toggleBtn.onclick = toggle;
</script>

</body>
</html>

 

고생 많으셨습니다.