My footsteps

자바스크립트 / 6 본문

국비수업/수업정리

자바스크립트 / 6

밀김 2023. 3. 28. 10:26
728x90

 

 

 

 

 

 

 

 

 

 

//객체로 위의 데이터들을 한번에 묶을수 있다

var move = [50+20];
var xes = [40, 40+50+20, 40+50+20+50+20, 40+50+20+50+20+50+20];
var yes = [30, 30, 30+50, 30+50];
let colors = ["yellow","green","blue","red"];

var boxes = [
    {x:40, y:30, color:"yellow"},
    {x:40, y:30, color:"yellow"},
    {x:40, y:30, color:"yellow"},
    {x:40, y:30, color:"yellow"},
];

 

var boxes = [
    new Box(30,30,"yellow"), //이런식으로 배열 안에 객체를 생성해줄수도 있다.이방법이 직관적이여서 추천!!
    {x:40, y:30, color:"yellow"}, //요것도 객체 형식임.하지만 이 방식은 어떤 데이터인지 한눈에 알수 없기 때문에 별로 좋은 방법은 아니다
    {x:40, y:30, color:"yellow"},
    {x:40, y:30, color:"yellow"},
    {x:40, y:30, color:"yellow"},
];
var boxes = [
    new Box(30,30,"yellow"),
    new Box(40+50+20,30,"green"),
    new Box(40+50+20+50+20,30,"blue"),
    new Box(40+50+20+50+20+50+20,30,"red"),
];
//요렇게 하기

 

 

- add() > 함수를 호출해라

new add() > 빈객체를 만들어서 초기화하면서 호출해라 (사실상 object의 객체기 때문에 완전 빈건 아니다)

 

- 자바스크립트는 모든 함수에서 this를 쓸수있다(변수 선언하지 않고도 쓸수있는데 그러면 자동으로 window가 붙는다)

 

- this == window

 

- 자스에서는 기능을하는 함수(소문자)를 만들건지, 아니면 객체를 초기화하는 생성자(첫글자 대문자,컨스트럭터)를 만들건지 잘 생각하고 만들어야한다

 

 

function Box(x,y,color){
    this.x = x || 0; //초기화 되지 않으면 0을 넣어주고 초기화가 되면 x값을 넣어준다
    this.y = y || 0;
    this.color = color || "black"; //초기화 되지 않으면 color를 넣어주고 초기화가 되면 black을 넣어준다
}

 

 

function Box(x,y,color){
    this.x = x || 0; 
    this.y = y || 0;
    this.color = color || "black"; 
}


var boxes = [
    new Box(30,30,"yellow"),
    new Box(40+50+20,30,"green"),
    new Box(40+50+20+50+20,30,"blue"),
    new Box(40+50+20+50+20+50+20,30,"red"),
];

for(var box of boxes){
    var x = box.x;
    var y = box.y;
    var color = box.color;

    ctx.fillStyle = color;
    ctx.fillRect(x,y,50,50); 
}
//이런식으로 꺼내서 볼수있다

 

 

 

 

 

- 캡슐화해서 정리한 코드인데..문제점이 많다. draw가 계속 네번이 호출되기 때뮤네

function Box(x,y,color){ 
    this.x = x || 0; //왼쪽 x는 Box본인의 x,오른쪽 x는 위 괄호에서 매개인자로 받은 x 
    this.y = y || 0;
    this.color = color || "black";
    //자스에서 this는 생략이 불가능하다

    this.draw = function(ctx){ //박스를 그려주는 새로운 함수 정의
        var x = this.x; //this.x는 Box의 this가 아니라 boxes의 this다
        var y = this.y;
        var color = this.color;
        //box에 있는 x,y,color를 호출하기 때문에 this를 붙여준다

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

var boxes = [
    new Box(30,30,"yellow"),
    new Box(40+50+20,30,"green"),
    new Box(40+50+20+50+20,30,"blue"),
    new Box(40+50+20+50+20+50+20,30,"red"),
];

for(var box of boxes){ //for of는 객체를 순환할때 사용함
    box.draw(ctx); //box가 ctx를 갖고 있지 않으니 인자로 넣어준다
}

 

 

https://wormwlrm.github.io/2019/03/04/You-should-know-JavaScript-this.html.html

 

JavaScript 개발자라면 꼭 알아야 할 this - 재그지그의 개발 블로그

JavaScript에서 흔히 혼동되는 this에 대한 개념을 정리해봅니다.

wormwlrm.github.io

 

 

- 키와 값을 주고 중괄호로 묶으면 객체가 된다

 

 

 


 

 

<프로토타입>

 

- prototype : 기본으로 하겠다 

 

- 프로토 타입을 정의하면 기본값으로 어디서든 사용이 가능하다(점 붙이고)

 

- 프로토타입 접근 방법: 자료형을 통해 접근한다,객체 getPrototypeOf 를 통해 직접 접근한다

 

Box.prototype = {
    kor:50
}

new Box().kor=70;

console.log(new Box().kor);
console.log(new Box().kor);
//답은 50 50 이 나온다. 70이 나오게 하려면

for(var box of boxes){ //for of는 객체를 순환할때 사용함
    box.draw(ctx); //box가 ctx를 갖고 있지 않으니 인자로 넣어준다
}


Box.prototype = {
    kor:50
}

new Box().kor=70;
Box.prototype.kor=80; //자료형에 직접 접근

console.log(new Box().kor);
console.log(new Box().kor);



Box.prototype = {
    kor:50
}

var box = new Box();
// box.kor = 100;
var boxProto = Object.getPrototypeOf(box); //객체에 직접 접근
boxProto.kor = 200; 

console.log(new Box().kor);
console.log(new Box().kor);

 

 

 

 

 

 

- hasOwnProperty() 메소드는 객체가 특정 프로퍼티를 가지고 있는지를 나타내는 불리언 값을 반환함(갖고있으면 true,없으면 false)

Box.prototype = {
    kor:50
}

var box = new Box();
var boxProto = Object.getPrototypeOf(box);
boxProto.kor = 200; 

console.log(Object.hasOwn(box,"kor")); //false
console.log(Object.hasOwn(boxProto,"kor")); //true

console.log(new Box().kor);
console.log(new Box().kor);


//-------------------
console.log(Object.hasOwn(box,"kor")); //true
console.log(box.hasOwnProperty("kor")); //true

console.log(Object.hasOwn(boxProto,"kor")); //false
console.log(boxProto.hasOwnProperty("kor")); //flase

 

 

    this.draw = function(ctx){
        var x = this.x;
        var y = this.y;
        var color = this.color;

        ctx.fillStyle = color; 
        ctx.fillRect(x,y,50,50); 
    }
    
    
//위의 함수를 프로토타입으로 바꿔서 정의하기. 이렇게 하는 이유는 매번 함수나 객체를??만들지 않고
//기본타입(프로토)로 지정해놓으면 정의할때만 쓸수있어서?프로토 타입은 모두 공유할수 있는 공공재... 하 뭐라는거애ㅇ
Box.prototype = {
    draw:function(){ //draw가 키,function이 값이 된다
        var x = this.x;
        var y = this.y;
        var color = this.color;
        //box에 있는 x,y,color를 호출하기 때문에 this를 붙여준다

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

 

 

 

 


 

 

 

 

<ES6>

 

- 자바스크립트는 모듈화라는 개념이 없다 (파일을 나눠도 같은 변수명을 쓰면 오류가 난다. 고립화가 존재하지X)

하지만 es6에서는 이런 문제가 해결된다

 

- import를 통해 다른 자스 파일을 사용할수 있다

 

 

import B from './box.js';
//받은 Box를 B라고 이름을 바꾼다. 그래서 Box라고 되어있던 이름들도 B로 바꿔줘야함

/** @type {HTMLCanvasElement} */
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");


var boxes = [
    new B(30,30,"yellow"),
    new B(40+50+20,30,"green"),
    new B(40+50+20+50+20,30,"blue"),
    new B(40+50+20+50+20+50+20,30,"red"),
];

for(var box of boxes){
    box.draw(ctx); 
}
function Box(x,y,color){
    this.x = x || 0; 
    this.y = y || 0;
    this.color = color || "black";
}

Box.prototype = {
    draw:function(ctx){ //ctx는 여기 없으니 인자로 꼭 써줘야한다 
        var x = this.x;
        var y = this.y;
        var color = this.color;

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

export default Box;
//내보내기

- html에는

 <script type="module" src="game.js" defer="defer"></script

타입-모듈을 넣어줘야한다

 

 

 

 

 

 

 

 

 

728x90

'국비수업 > 수업정리' 카테고리의 다른 글

자바스크립트 / 7  (0) 2023.03.29
자바스크립트 복습  (0) 2023.03.28
웹퍼블리싱(CSS) / 2  (0) 2023.03.27
자바스크립트 / 5  (0) 2023.03.27
HTTP / URL구조  (0) 2023.03.24