자바스크립트 개념(Object Oriented Programming)

Jung Hyun Kim·2020년 6월 5일
0

자바스크립트 개념(Object Oriented Programming)

Intro to Object Oriented Programming

Why OOP?

-Organize our codes for dintinct patterns of object.

생성자(Constructor)/생성자 함수(Constructor function)

  • 생성자는 앞자리 대문자로 해주어 일반 함수와 구분을 준다.
  • 함수 내부에는 return value가 없고 this:something 이렇게 정의해준다
  • 인스턴스를 만들려고 생성자를 사용하는 것
  • This 를 쓰려면 new와 함께 why? this는 윈도우 객체 이기 때문에 확인을 못한다.
function Color(r,g,b) {
this.r=r;
this.g=g;
this.b=b;
}

Color.prototype.rgb = function () {
  const { r,g,b} = this;
  return `rgb(${r},${g},${b})`;

new Color(255,40,100); // 생성자 함수를 호출할때는 new를 붙임
  • 계속해서 사용해야 하는 method에서 유용하게 사용될 수 있음!

Class

-Javascript가 객체지향 언어는 아니지만 class를 통해 프로그램을객체로 구성하고 객체들 간에 서로 상호작용 하도록 작성하는 방법이다.(css의 class값 아님주의)
-Class 함수가 Constructor함수보다 편리한 이유는 한번에 정의할수 있기때문,(Constructor함수는 나중에 object에 추가하는형태로 해줘야하는 반면, 클래스 함수는 안에 다 추가할 수 있다.)
-class함수를 정의하고 바로 constuctor() {} 함수를 입력하는데, 그앙에 넣고자 하는 함수를 넣는다.

class Color {
  constructor(r,g,b) {
    this.r=r;
    this.g=g;
    this.b=b;
    this.name= name;
  }
  greet() {
    return `Hello I am ${this.name}`;
  }

const c1=new Color(255,67,89,'tomato');
console.log(c1) 

//아래값을 반환한다.
{
  r:255
  g:67
  b:89
  name:'tomato'
}

console.log(Color.greet);
//'Hello I am tomato' 를 반환한다.
profile
코린이 프론트엔드 개발자💻💛🤙🏼

0개의 댓글