배움 __IL/TIL 1기

TIL : 91번째- 230417 [4-3-월]

Mo_bi!e 2023. 4. 17. 16:19

I. 피그마 특강

정리
1. 컨텐트 모우기 그리고 배치하기
-> 이 경우 레이아웃그리드를 이용

2. 배치 hug 와 다시잡아주기
-> 이 경우 패딩을 유의하자

3. 버튼 combine 해서 자유 자재로 사이즈 조정
-> 같은 속성을 가진애들 끼리 가능

4. 자주 쓰는 스타일은 명칭을 넣어서 지정해주기

II. ES6 복습

1. js import

(1) import 해보기

1) html 에다가 추가해보기

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    
    <style>
        
        
    </style>

    <script src="shape.js" defer="defer"></script>

</head>
<body>
    
    <!-- <canvas></canvas> -->

</body>
</html>

defer 잊지말자

원치않다면 windows.onload를 이용하면된다.

 

2) js 에서 조작하기

let canvas = document.createElement("canvas");

canvas.width = 500;
canvas.height = 400;
canvas.style.border = "solid 1px black";

//위 아래 둘다 가능해 
// canvas.style.borderColor = "blue";
canvas.style["border-color"] = "blue";

document.body.append(canvas);

let ctx = canvas.getContext("2d");

원래는 <body> 태그 안에 줄 수있다 

그렇지만 스타일은 동적으로 줄 수 있어야해

 

2. canvas 에서 사각형 그리기

(1) 직접그려보기 

1) 하나씩 그리기

ctx.fillStyle = "red";
ctx.fillRect(10,10,50,50);

ctx.fillStyle = "yellow";
ctx.fillRect(30,30,50,50);

이렇게 그려지는 거야! 하지만 이렇게 하나씩하는것이 과연옳을까?

 

2) 여러도형을 그려보기 : 구조화를 이용해서

ctx.fillStyle = "red";
ctx.fillRect(10,10,50,50);

ctx.fillStyle = "green";
ctx.fillRect(10+50+20 ,10,50,50);

ctx.fillStyle = "yellow";
ctx.fillRect(10+100+ 40 ,10,50,50);


ctx.fillStyle = "purple";
ctx.fillRect(10+150+ 60 ,10,50,50);

// ----구조화----

let color = ["red", "green", "yellow", "purple"];
let x = 10;
let y = 70;

let size = 0;
let gap = 0;

for(i of color){
    console.log(i);

    ctx.fillStyle = i;
    ctx.fillRect(x + size + gap ,y,50,50); 

    size += 50;
    gap += 20;
}

아래쪽 방식처럼 반복문을 이용해서 할 수 있다.

(2) 디스트럭처링

반복문을 쓰기 전에 디스럭처링으로 보다 용이하게 이용이 가능하다.

 

1) 배열 디스트럭쳐링

let kors = [30,40,50];
let [kor1, kor2, kor3] = kors;

console.log(`kor1 = ${kor1}, kor2 = ${kor2}, kor3 = ${kor3}`);

[kor1,kor2 ] = [kor2, kor1];
console.log(`kor1 = ${kor1}, kor2 = ${kor2}, kor3 = ${kor3}`);

2) 바로 뽀개기

let both = [
    
    new Box(),
    new Box(30,40,50,50, "red")
];
// -첫번째 box의 color과 width 를 얻기

{
    let [{color, width} = b1, b2] = both;

    // console.log(b1);

    // let {x, y ,width:w, height:h , color} = b1
    console.log(color)
    console.log(width);

}

 

 

b1 을 바로 color, width 에 뽀개기가 가능하다

이렇게 디스트럭쳐링을 한번에 해서 color과 width 를 출력하기!

 

(3) 함수로 이용해보기

1)

function Box(x,y,w,h,color){
    this.x = x || 0;
    this.y = y || 0;
    this.width = w || 50;
    this.height =h || 50;
    this.color = color || "black";
}

//let boxes = [
//new Box(100,100,50,50,"black"),
//new Box(100,100,50,50,"green"),
//new Box(100,100,50,50,"blue"),
//new Box(100,100,50,50,"red"),
//]

//----------
let gap2 =20;
let colorAar = ["red", "green", "yellow", "purple"];
let boxes2= [];

// 위 new box 반복되어서 push방식으로 갈음함
for(let i = 0 ; i < 4 ; i ++){
    boxes2.push(new Box(i * (50 + gap2), 0, 50, 50 , colorAar[i]));
}

인자가 없는경우를 대비해서 ||를 이용한 기본값 설정이 가능하다.

 

좀 더 구조화해서 함수로 해보자!

이 경우 배열을 반복하기 보다 push를 이용해보자!

 

2)

box.js로 나누기

여기서 ctx등을 이용해서 그림을 그리기!

 

<shape.js>

let gap2 = 20;
let colorAar = ["red", "green", "yellow", "purple"];
let boxes2= [];

// 위 new box 반복되어서 push방식으로 갈음함
for(let i = 0 ; i < 4 ; i ++){
    boxes2.push(new Box(i * (50 + gap2), 0, 50, 50 , colorAar[i]));
}

for(let box of boxes2){
    box.draw(ctx);
}

<box.js>

// 박스정의
function Box(x,y,w,h,color){
    this.x = x || 0;
    this.y = y || 0;
    this.width = w || 50;
    this.height =h || 50;
    this.color = color || "black";

    // this.draw = function(ctx){
        
    //     let {x, y ,width:w, height:h , color} = this;
            
    //     ctx.fillStyle = color;
    //     ctx.fillRect(x,y,w,h,color);
    // }


}

//프로토타입에다가 정의하기! -> 모든 박스객체가 공유하게됨!
Box.prototype = {
// let proto ={
    // kor : 10,
    draw : function(){

        let {x, y ,width:w, height:h , color} = this;
            
        ctx.fillStyle = color;
        ctx.fillRect(x,y,w,h,color);
    }
};

함수로 만들고나서 prototype을 별도로 설정이 가능하다 

바로 지정해서 넣을수도 있고, 별도로 변수를 설정해서 넣을 수 도있다. (생성자 함수 기능을 위해서)

 

3. class 이용하기

(1) 함수를 class로

1) 들어가며

함수는 두가지 로직을 가지는 함수, 생성자함수 두가지로 나누어져

class Box{

    constructor(x=0, y=0, w=50, h=50, color="black"){
        this.x = x ;
        this.y = y ;
        this.width = w;
        this.height =h;
        this.color = color;
    }

    draw(){
        let {x, y ,width:w, height:h , color} = this;

        ctx.fillStyle = color;
        ctx.fillRect(x,y,w,h,color);
    }

이런경우 class 로 하는게 나을 수 있어 class 로 하는데 문제가 있어

prototype으로 정의를 어떻게 할까? 손쉽게 클래스안에 멤버메소드로 선언해주면 돼!

 

기존 생성자(프로토타입)의 역할은 constructor를 이용

그런데 이 경우 어떤문제가 있냐하면 기본값을 주어야했는데, 이제 || 를 쓸 필요가 없어

기본값을 인수에다가 바로 넣어주면 돼! 이전보다 모호한 부분이 사라지게 되었어

 

2)

console.log(boxes2[0].kor);
console.log(Object.hasOwn(boxes2[0], 'draw'));

console.log(typeof Box.prototype);

//function 이름으로 prototype 얻기
let proto = Box.prototype;
console.log(Object.hasOwn(proto, 'draw'));

draw 가 boxes2[0]의 것은 아니라고 false가 출력이 되었어

그렇다면 prototype인 것인가

이를 위해서 Box의 prototype으로 확인을 하니 true가 출력이 되었어

 

우리는 클래스 만들었는데, 클래스도 function이고, 클래스 안의 것은 프로토타입이야

우리가 꺼낼수 있다는것은 객체모델은 프토로타입과 비슷한거야!

 

**우리가 ES5를 모르고 클래스로만 공부하면 프로토타입 지식이 없어

(2) 은닉화

1)

class의 멤버에 대한 은닉성을 담보하자! 멤버들 x,y등을 노출할수 없게하자! # 을 해준다

class Box{

    #x;

    constructor(x=0, y=0, w=50, h=50, color="black"){
        this.#x = x ;
        this.y = y ;
        this.width = w;
        this.height =h;
        this.color = color;
    }

    draw(){
        let {x, y ,width:w, height:h , color} = this;

        ctx.fillStyle = color;
        ctx.fillRect(x,y,w,h,color);
    }

}

x 는 private이기 때문에 아래 draw()에서 뽀개기를 하면 undefined가 발생해

이런경우를 대비하기위해서 별도로 작업을 해주어야해!

class Box{

    #x;

    constructor(x=0, y=0, w=50, h=50, color="black"){
        this.#x = x ;
        this.y = y ;
        this.width = w;
        this.height =h;
        this.color = color;
    }

    getX(){
        return this.#x;
    }
    setX(){
        this.#x = x;
    }

    draw(){
        let {y ,width:w, height:h , color} = this;
        let x = this.#x;

        ctx.fillStyle = color;
        ctx.fillRect(x,y,w,h,color);
    }

}

이렇게 draw에다가 별도로 해주는것과 동시에

외부에서 접근하기 위해서 get, set 을 이용해준다.

 

let box10 = new Box();
box10.x++;
console.log(`x:${box10.x}`);

2)

다른파일(shape.js)에서 증감연산자 이용이 안되는 문제가 있어

그런데 getX(), setX()불편해 보다 쉽게 가능해

get x(){
    return this.#x;
}
set x(x){
    this.#x = x;
}

(3) Object 관련

1) 프로퍼티 정의

let obj = {x: 10 , y : 20};
Object.defineProperty(obj, 'z',{
    value: 30,
    writable:false
})

obj.y= 50;
obj.z= 60;
console.log(obj);

writable:false 를 했다 더이상 쓰기를 할수없다는 의미이다

결국 z는 상수화 되어서 더이상 변경이 되지않고있다

그래서 최초에 선언한 z값은 그대로 30이다

 

하지만 y의 경우 그렇지않게 50으로 변경되었다.

2) enumeralbe 

let obj = {x: 10 , y : 20};
Object.defineProperty(obj, 'z',{
    value: 30,
    writable:false,
    enumerable:true
})

enumerable 하면... 반복문에서 속성을 반환하는 방식에 대해서 지정이 가능해

false를 하면 for-in 인 경우 z가 반환이 안돼

true를 하면 z가 반환이 돼 

 

3) preventExtensions

let obj = {x: 10 , y : 20};
Object.preventExtensions(obj);
Object.defineProperty(obj, 'z',{
    value: 30,
    writable:false,
    enumerable:true
})

for(let i in  obj){
    console.log(i);
}

preventExtensions 를 하면 더이상 obj 에서 z를 추가할 수 없게 돼!


1. 보충

(1)

 

 

 

2. 회고 

1) ES6 에 대해서 전반적으로 복습을 해서 따라갈만은한데, 사실 예전에 정리했던 내용을 한번이라도 복습을 하면은 훨씬 수월할수 있지않을까 생각한다!

 

2) 피그마의 경우 레이아웃잡고 하는 방식은 예전에 라이노로 디자인을 했던 기억이나서 흥미롭다!

'배움 __IL > TIL 1기' 카테고리의 다른 글

TIL : 93번째- 230419 [4-3-수]  (4) 2023.04.19
TIL : 92번째- 230418 [4-3-화]  (0) 2023.04.18
TIL : 88번째- 230411 [4-2-화]  (0) 2023.04.11
TIL : 87번째- 230410 [4-2-월]  (0) 2023.04.10
TIL : 86번째- 230407 [4-1-금]  (0) 2023.04.07