WEB/javascript

04. javascript object oriented programing

slow333 2023. 1. 29. 11:21

function 형태로 지정 하는 방식

  •  전체 내용이 초기화 구문과 같음(단, 변수 타입 지정은 없음) ==> java의 simple 한 버젼
  •  변수 this의 개념은 java와 같음
  •  함수를 통합해서 지정하는 방식
  •  함수는 class와 같이 별도로 지정해서 사용해야함

* class 형태로 지정하는 방식이 있으며 function 형태로 oob를 구현하는 것은 좀 이상함

* 본래 js가 함수형 언어로 이를 활용한 방식이기는 하나 정의, 사용에 한계가 있음

function Person(name, age){ // 초기화를 위한 args
  this.name = name; // 생성자 정의 방식
  this.age = age;
  this.today = new Date();
  this.luckyNumber = function () {  // 함수 정의
    return Math.round(Math.random() * this.age) + 1;
  }
  this.sum = function () {
    return this.age + this.today.getDate();
  }
}

let NewPerson = new Person('프리맨', 55);
console.log(NewPerson);
console.log(NewPerson.luckyNumber());

함수를 분리하는 방법 => prototype으로 정의함

function PersonData(name, age) { // 초기화를 위한 참조 변수
  this.name = name; // 생성자 정의 방식
  this.age = age;
  this.today = new Date();
}
PersonData.prototype.luckyNumber = function () {  // 함수 정의
  return Math.round(Math.random() * this.age) + 1;
}
PersonData.prototype.sum = function () {
  return this.age + this.today.getDate();
}
// 위와 같이 하면 새로운 객체를 생성시에 함수에 대해서 별도로 정의해서 사용 가능
let kim = new PersonData('kim', 55);
kim.sum = function () { // 함수에 대해 별도로 지정 해야함 => 좀 불편함
  return this.age + this.today.getHours();
};
console.log(kim);
console.log(kim.sum(),'🤪');

class를 사용한 class 지정 방식, java와 동일함 => 권장 방식

  • 생성자 지정 방식이 constructor를 사용함
  • method 정의는 반환값이 없는 방식으로 지정하면됨
class People{
  constructor(name, age, address) {
    this.name = name;
    this.age = age;
    this.address = address;
  }
  now() {
    return new Date();
  }
}

let p1 = new People('maxim', 55, 'daejon si');
console.log(p1,'\n', p1.now());

// 상속 방식 ==> 자바와 동일
class InherentPeople extends People{
  newAge(){
    return this.age -10;
  }
}
let newP = new InherentPeople('kim', '33', 'seo gu');
console.log('new age : ',newP.newAge());
console.log( 'InherentPeople : ', newP);

// super 이용 방식 java와 동일
class SuperPeople extends People{
  constructor(name, age, address, children) {
    super(name, age, address); // 조상의 것은 조상이 초기화 하게 함
    this.children = children;
  }
  newAge(){
    return Number(super.now().getDate()) + Number(this.age); // 형변환
    // parseInt(), parseFloat() 도 있음
  }
}
let superPeople = new SuperPeople('kim', '33', 'seo gu', 2);
console.log( superPeople);
console.log('new age : ',superPeople.newAge());

js에서는 객체에서 링크를 통해 상속을 지정 가능

let superObj = {superVal: 'super'}
// let subObj = {subVal: 'sub'}
// subObj.__proto__ = superObj; // ==> 권장하지 않음
let subObj = Object.create(superObj);  // ==> 이 방식을 권장
// 상속 이라는 개념 보다는 객체를 다시 생성해서 사용하는 방식...
// debugger; ==> 이 걸하면 여기서 멈춤
subObj.subVal = 'sub';
console.log(subObj.subVal);

let son = {
  name: 'son',
  first: 10, second: 30,
  sum: function () {
    return this.first + this.second;
  },
}

let sonSun = Object.create(son);
sonSun.name = 'kim';
sonSun.first = 20;
sonSun.second = 30;
sonSun.avg = function () {
  return (this.first + this.second)/2;
}; // => 이걸 쓰면 뭐하러 쓰는지 모르 겠음...

console.log(sonSun.sum());
console.log(sonSun.avg());

call 함수

let kim1 = {name: 'kim', f:10, s: 20}
let lee = {name: 'lee', f:22, s: 33}

function sum(prefix){
  return prefix + (this.f + this.s);
}

console.log(sum.call(kim1,'call prefix : '))
console.log(sum.call(lee,'call prefix : '))

bind 함수 ==> 호출 시에는 함수 형태로 호출 해야함

let leeBind = sum.bind(lee, 'bind call : ')
console.log(leeBind());

class 형태가 아닌 function을 통해 객체를 구현하는 방법

  • constructor를 초기 입력값으로 지정해서 사용 가능
  • 내부에 다른 함수를 갖을 수 없음...
  • 상속 개념과 객체를 생성해서 재 사용하는 개념의 차이(is equeal OR has it)
  • 가능하면 class를 정의해서 사용하는 것이 좋음(class와 같은 내용임....)
function NewFunPerson(name, age, address, something) {
  FunPerson.call(this, name, age, address); // 함수를 호출해서 사용
  this.something = something;
}

// FunPerson의 method를 상속받기 위한 방법
// NewFunPerson.prototype.__proto__ = FunPerson.prototype;
// prototype에 있는 것을 상속 받아서 prototype으로 넣어 줘야 함
// 기존 객체를 대체해서 기존에 prototype에 정의한 내용을 초기화함
NewFunPerson.prototype = Object.create(FunPerson.prototype);
// NewFunPerson.prototype.constructor = NewFunPerson;
// 상속이 이루어 진 후에 객체에 대한 추가 함수를 정의 해야함(순서 다르면 애러 나옴)
NewFunPerson.prototype.newFun = function () {
  return Math.random();
};

let newFunPerson = new NewFunPerson('new', 33, 'some', 'call me');
console.log(newFunPerson.newAge());
console.log(newFunPerson.newFun());

console.log(newFunPerson.constructor)

전반적으로 객체 개념은 java와 동일하나

js의 특성으로 function, arrayMap 형태를 활용해서 상속을 구현 가능

__proto__, prototype, Object.create() 등을 활용하여 간단하게 상속을 구현할 수 있으나 좀 혼란 스러움

전반적으로 위 방식 보다는 class를 정의해서 사용하는 것이 전반적으로 코드가 깔끔함

oob에서는 class를 사용하는 방식을 권장하고 있음

'WEB > javascript' 카테고리의 다른 글

03. javascript array, object array  (0) 2023.01.29
02. jQuery 사용(javascript)  (0) 2023.01.27
01. javascript 기본 변수 정의  (0) 2023.01.27
00. javascript 개요  (0) 2022.12.14