JavaScript 05 함수02

지현·2022년 5월 25일
0

Javascript / TypeScript

목록 보기
4/16
post-thumbnail

객체

자바스크립트에서 객체를 생성하는 방법

  1. 리터럴(literal)표기 방법
  2. 생성자 함수(constructor function)
  3. Object.create() 메소드 이용

리터럴 표기

const cat = {
    name: 'momo',
    gender: 'Male',
    family: '러시안블루',
    age : 5,
    sayHello : function(){
        console.log('안녕하세요'+this.name+'입니다.')
    }
}
cat.sayHello()
console.log(cat.name) //점 표기법
console.log(cat['family']) //대괄호 표기법

나이 20살 이름 김철수 사는곳은 서울 표시하는 코드

const chul = {
    name: '김철수',
    age : 20,
    place : '서울',
    hello : function(){
        console.log('안녕 내 이름은'+this.name+'나이는'+this.age+this.place+'살아')
    }
}
chul.gender = 'male'//점 표기법
// chul[gender] = 'male'//대괄호
console.log(chul);

생성자함수

  • new 연산자로 객체를 생성할 것이라 기대하고 만든 함수
  • 생성자 object를 여러개 찍어주는 것
  • 구조가 동일한 여러개의 객체 생성 가능
  • 생성자함수 이름 첫 글자는 대문자로(암묵적인 규칙)(생성자임을 알리기 위함)
  • 함수를 호출할 때 new라는 연산자와 함께 호출해야 해당 함수가 생성자 함수로 동작함
  • new 없이 생성자 함수 호출하면 그냥 일반 함수됨
    생성자 함수 쓸 때 this 연산자 써야해
  • 생성자 안에서 this.프로퍼티이름 에 값을 대입하면 그 이름을 가진 프로퍼티 값이 할당된 객체가 생성된다. (this는 생성자가 생성하는 객체)
function Chul(name, age,place) {
    this.name = name;
    this.age = age;
    this.place = 'seoul' 
}
const Chul1 = new Chul('김철수', 20)
const Chul2 = new Chul('김영희', 29)
const Chul3 = new Chul('조민경', 33)
console.log(Chul1)
console.log(Chul2)
console.log(Chul3)
  • 생성자는 객체를 생성하고 초기화 하는 역할
  • 생성자를 사용하면 이름은 같지만 프로퍼티 값이 다른 객체 여러개를 간단하게 생성 가능

반지름으로 지름 구하는 코드

function Circle(radius) {
    this.radius = radius;
    this.getDiameter = function () {
        return this.radius * 2
    }
}
const circle1 = new Circle(5)
const circle2 = new Circle(10)
console.log(circle2.getDiameter())
console.log(circle1)

이름 , 국, 영, 수 , 평균 kim lee park

function Avg(name, kor, eng, math) {
    this.name = name;
    this.kor = kor;
    this.eng = eng;
    this.math = math;
    this.getInfo = function () {
        return ' name : ' + this.name + ' kor : ' + this.kor + ' eng : ' + this.eng + ' math : ' + this.math
    }
}
Avg.prototype.getAvg = function () {
    return ' avg : ' + (this.kor + this.eng + this.math) / 3
}
const avg1 = new Avg('kim', 90, 98, 87)
const avg2 = new Avg('lee', 80, 78, 67)
const avg3 = new Avg('park', 50, 60, 70)
console.log(avg1.getAvg())
console.log(avg1.getInfo(), avg1.getAvg())
console.log(avg2.getInfo(), avg2.getAvg())
console.log(avg3.getInfo(), avg3.getAvg())
console.log(Avg.prototype) // {} object  { getAvg: [Function (anonymous)] }

프로토타입

  • 부모의 부모, 기본적으로 가지고 있는 원형
  • JavaScript는 흔히 프로토타입 기반 언어(prototype-based language)라 불립니다.
  • 모든 객체들이 메소드와 속성들을 상속 받기 위한 템플릿으로써 프로토타입 객체(prototype object)를 가진다.

자바스크립트의 모든 객체는 최소한 하나 이상의 다른 객체로부터 상속을 받으며, 이때 상속되는 정보를 제공하는 객체를 프로토타입(prototype)이라고 합니다.

모든 오브젝트는 원형을 가지고 있고, 모든 오브젝트의 프로토타입은 오브젝트이기 때문에 오브젝트의 속성 모두 가지고 있다.

찾는 값이 없으면 그 부모한테 가서 있는지 찾고 점점 위로 올라간다. 프로토타입은 최상단

 <script>
        function Student(a,b){
            this.name = a;
            this.name = b;
        }
        Student.prototype.address='korea'
        var student1 = new Student('lee',20)
        var student2 = new Student('kim',30)

        console.log(student1.address) 
// 1. 내가 address 값을 가지고 있는지 검사 
// 2. 부모의 원형 prototype을 검사 
// 3. 부모의 부모 탐색 ... 
     console.log(Student.prototype)

    </script>

의 콘솔창

가격 * 0.4로 tax 출력하는 코드

function Product(item,price){
    this.item = item;
    this.price = price;
    this.getInfo = function () {
            return 'item : '+ this.item + ', price : '+ this.price
        }
}
Product.prototype.getTax = function(){
    return (this.price*0.4)
}
  • 인스턴스 오브젝트가 값을 직접 소유하게 만들고 싶으면 construct에 만들기

  • prototype만 가지고 있고 참조해서 사용하고 싶으면 prototype에 만들어서 상속시키기

  • 인스턴스는 prototype 없고, constructor만 prototype갖는다. 부모에 해당하는 생성자 함수에 프로토타입을 추가할 뿐

    const product1 = new Product('book',15000)
    const product2 = new Product('game',25000)
    const product3 = new Product('cd',6000)
    console.log(product1.getInfo(),product1.getTax())
    console.log(product2.getInfo(),product2.getTax())
    console.log(product3.getInfo(),product3.getTax())
    console.log(product3.__proto__);```
    
    
    constructor 생성된 오브젝트는 prototype을 가지고 있지 않음, 
    부모요소 prototype 을 확인할때 __proto__ 속성을 허용하여 확인.
  • __proto__ : 부모 생성자의 프로토타입을 확인하는 속성 2. 오브젝트 끼리 상속할 수 있게 구현해준다.
const parent = {name : 'kim'}
const child ={}
child.__proto__=parent
console.log(child.name)

Object

const parent = {
    name : 'kim',
    age : 50
}

함수만들기

1. 생성자 함수로 만든다.
2. constructor로 만든다
3. Object <<모든 오브젝트를 만들 때 쓰는 생성자 함수 object.create()

  • const child = Object.create(parent)
    // 나의 부모요소의 프로토타입에 이거 넣어줘
    //나는 비어있고, 값은 찍힘
console.log(child.name)
console.log(child.age)
const item={title:'tee',price:5000}
const itemChild = Object.create(item)
itemChild.price=7000
console.log(itemChild.price)
console.log(itemChild)
const itemChildChild = Object.create(itemChild)
console.log(itemChildChild.price)

class

  • 생성자 함수 사용해서 여러개의 오브젝트 만들어서 사용
  • prototype을 이용해서 상속을 받아 값을 참조
    => ★☆ES6는 클래스class 사용 ★☆ 짱중요
  •     constructor(매개변수) {
            변수할당;
            변수할당;
        }
        ```
    으로 쓴다.
class User {
    constructor(name, age) {
        this.name = name;
        this.age = age;
        /* this.hi = function(){
            console.log('이름은 ' + this.name + ' 나이는 ' + this.age)
        } */
    }
    hi() {
        console.log('이름은 ' + this.name + ' 나이는 ' + this.age)
    }
}
const user1 = new User('김길동', 10)
const user2 = new User('이순희', 15)
console.log(user1.hi())

people1 {name :'새싹' hello()=>반갑습니다 welcome()=>방문해주셔서 감사합니다 메서드 갖고 있음} 만드는 코드

class People {
    constructor(name) {
        this.name = name;
    }
    hello() {
        console.log(this.name+'반갑습니다.')
    }
    welcome() {
        console.log(this.name+'방문해주셔서 감사합니다.')
    }
}
const people1 = new People('새싹')
console.log(people1,people1.hello(),people1.welcome())
console.log(people1)//people1__proto__ => Object.getPrototypeOf(people1)
console.log(Object.getPrototypeOf(people1))

extends(상속)

class User { 
    constructor(name, age) { //constructor은 생성자
        this.name = name;
        this.age = age;
    }
    hi() {
        console.log('이름은 ' + this.name + ' 나이는 ' + this.age)
    }
}

라고 User 메서드를 정의한 후

const user1 = new User('홍길동', 10)
const user2 = new User('김철수', 25)
console.log(user1)
console.log(user2)
user2.hi()

new연산자로 메서드에 프로퍼티 추가

class AddUserLocation extends User {
    constructor(name, age, location) {
        super(name, age)
        this.location = location;
    }
    hi() {
 console.log('유저의 위치는 ' + this.location + '입니다.') 
      // 덮어쓰기 (오버라이딩)
    }
}

에서 class AddUserLocation extends User 처럼 extends 이용하여 User의 값 상속할 수 있다.
super 는 부모 클래스를 상속하는 것, 얘를 안 적어주면 위에 있는 값이 들어오지 않는다.

extends 예제

// Dog 클래스 color랑 weight, gender
// Dog 확장 시켜서 Cat만들기 위 속성 다 가지고 있고, 거기에 name 속성도 추가하기

class Dog {
    constructor(color, weight, gender) {
        this.color = color;
        this.weight = weight;
        this.gender = gender;
    }
}
const dog1 = new Dog('white', '2kg', 'girl')
const dog2 = new Dog('black', '5kg', 'boy')
console.log(dog1)
console.log(dog2)
class Cat extends Dog {
    constructor(color, weight, gender, name) {
        super(color, weight, gender);
        this.name = name;
    }
    goyang() {
console.log(
'고양고양' + this.color + this.gender + this.weight + this.name)
    }
}
const cat1 = new Cat('cheese', '3kg', 'girl', 'miyu')
cat1.goyang()

접근자 프로퍼티 (getter/setter)

프로퍼티는 데이터 프로퍼티와 접근자 프로퍼티로 나눌 수 있다.

  • 데이터 프로퍼티 : 값을 저장하기 위한 프로퍼티
  • 접근자 프로퍼티 : 값이 없음, 프로퍼티를 읽거나 쓸 때 호출하는 함수를 값 대신 지정할 수 있는 프로퍼티
  • 접근자 : 객체 지향 프로그래밍에서 객체가 가진 프로퍼티 값을 객체 바깥에서 읽거나 쓸 수 있도록 제공하는 메서드
  • getter
    데이터를 가지고 오는 함수는 get 이라는 키워드를 사용한다.
    파라미터가 없는 함수
    return 값이 꼭 있어야 한다.

  • setter
    데이터를 입력, 수정해주는 set 이라는 키워드를 사용한다.
    파라미터가 꼭 힌개 있어야 한다.

ex)

const user = {
    name: '철수',
    age: '20',
    print: function () {
      console.log(`안녕하세요 ${this.name}입니다.
이번 정부부터 ${this.age -1}살이라구`)
    }
}

user.print()



const zzinUser = {
    get nameOut() { //출력
        return this._name //key값이랑 이름 같으면 안되니까 _ 붙여줌
    },
    set nameIn(value) { //입력
        if (value.length < 5) {
            console.log('글자수가 틀렸습니다.');
            return
        }
        this._name = value
    }
}

zzinUser.nameIn = 'jane'
console.log(zzinUser.name)

zzinUser.nameIn = 'janeeee'
console.log(zzinUser._name)

숫자를 입력 받아서 set get +10 출력

const number = {
    get outputNum() {
        return `출력값은 ${this._num+10}`;
    },
    set inputNum(value) {
        this._num = value;
    }
}

number.inputNum = 29;
console.log(number.outputNum)

입학년도 +4

class Student {
    constructor(name) {
        this.name = name;
    }

    get getEndYear() {
        return `${this.name}의 졸업년도는 ${this.startYear +4}년입니다.`
    }

    set setStartYear(year) {
        this.startYear = year;
    }
}

const student1 = new Student('김지현');
student1.setStartYear = 2016;
console.log(student1.getEndYear)

0개의 댓글