공부 기록/강의정리

[드림코딩 by 엘리] 자바스크립트 기초 강의_(2)

코딩걈자 2022. 2. 23. 19:42

1. class vs object

- class : 틀의 역할(template)

class Person{
    constructor(name, age){
        this.name=name;
        this.age=age;
    }

    speak(){
        console.log(`${this.name}:hello!`);
    }
}
  • 객체지향 언어의 특징, 캡슐화, 상속,,,
  • 한번만 정의(데이터는 x)
  • 속성(field) : name, age
  • method: speak()

 

- object: 틀에 데이터를 넣어 생성한 것(instanxe of a class)

const jieun=new Person('jieun',24);
console.log(jieun.name);
console.log(jieun.age);
jieun.speak();
  • 여러번 생성 가능
  • 실제 데이터가 들어있음

 

-Getter & Setter

class User{
    constructor(firstName,lastName,age){
        this.firstName=firstName;
        this.lastName=lastName;
        this.age=age;
    }

    get age(){
        return this._age;
    }
    
    set age(value){
        this._age=value<0?0:value;
    }
}
  • 잘못된 값을 방어하기위한 기능 (ex)나이는 0이상의 값만 가능)
  • get: 값을 return
  • set: 값을 설정
  • 무한루프 방지를 위해 age가 아닌 새로운 변수 _age사용

 

- Public vs Private vs Static

public: 어디서든 접근 가능

private: 객체를 생성해도 접근 불가능

static: 각 객체마다 할당되는 것이 아닌 class자체 / class.- 으로 접근 가능

 

- 상속 & 다양성

  • 상속: extends / 공통되는 것을 묶어 재사용
class Shape{
    constructor(width,height,color){
        this.width=width;
        this.height=height;
        this.color=color;
    }

    draw(){
        console.log(`drawing ${this.color} color of`);
    }
    getArea(){
        return this.width*this.height;
    }
}

//상속
class Rectangle extends Shape{}
const rec=new Rectangle(20,20,'blue');
rec.draw();

 

  • 다양성(오버라이딩): 필요한 메소드만 변경가능 / 부모의 메소드도 호출하고 싶을때에는 super.-
class Rectangle extends Shape{}
class Triangle extends Shape{
    getArea(){
        return (this.width*this.height)/2;
    }
}
//Rectangle class
const rec=new Rectangle(20,20,'blue');
console.log(rec.getArea()); // 400

//Triangle class
const tri=new Triangle(20,20,'red');
console.log(tri.getArea()); //200

 

- instanceof

클래스를 이용하여 만들어진것인지 확인하는 것 : true / false

console.log(rec instanceof Rectangle); //true
console.log(rec instanceof Triangle); //false
console.log(rec instanceof Shape); //true
console.log(rec instanceof Object); //true

🔔 부모 class는 true, 모든 객체는 Object를 상속한 것임

 

🔔 자바스크립트 object들 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference

 

JavaScript reference - JavaScript | MDN

This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more about this reference.

developer.mozilla.org

 

2.  Object

- Literals and properties

  • 여러가지 정보를 넣어야할때 불편함을 object로 묶어서 표현
  • object={ key : value }
    //선언 방법
    const obj1={}; //'object literal' syntax
    const obj2=new Object(); //'object constructor' syntax

- Computed properties

  • key는 string타입
console.log(jieun.name);
console.log(jieun['name']);
  • 보통 .(dot)을 이용하여 접근하지만, 실시간으로 원하는 key의 값을 가져올때는(input값을 사용할 때) [ ] 사용
function printValue(obj,key){
    console.log(obj[key]); //obj.key는 key라는 key를 찾는것이므로 오류 발생
}

printValue(jieun,'name');

 

- Constructor

function Person(name,age){
    //this={};
    this.name=name;
    this.age=age;
    //return this;
}
  • class 에서 객체를 만드는 것처럼 자동으로 Object 생성
  • 새로운 object를 만들고 return 하는것을 생략 가능
const person1=new Person('bob',20);
console.log(person1)

 

- in operator

key가 있는지 확인

console.log('name' in jieun); //true
console.log('random' in jieun); //false
console.log(jieun.random); //undefined

 

- for..in vs for..of

  • for(key in obj) :  객체의 key를 하나씩 대입
for(let key in jieun){
    console.log(key);
}
//name age
  • for(value of iterable) : 배열이나 리스트와 같은 순차적인 데이터를 접근
const array=[1,2,3]
for(let i of array){
    console.log(i);
}
//1 2 3

 

- cloning

  • 객체를 대입하면 같은 값을 가리키기 때문에 값이 같이 변경됨
const user={name:'jieun',age:'20'};
const user2=user;

console.log(user.name); //jieun

user2.name='coder';
console.log(user.name); //coder
  • 값만 복사하는 방법
//old way
const user3={};
for(let key in user){
    user3[key]=user[key];
}


//Object.assign
const user4=Object.assign({},user);

🔔 assign은 뒤 property로 값을 덮어줌

const fruit1={color:'red'};
const fruit2={color:'blue',size:'big'};
const mixed=Object.assign({},fruit1,fruit2);
console.log(mixed);

반응형