본문 바로가기
LEARN/JAVASCRIPT

[JS] JavaScript 객체 고급

by 아이엠제니 2022. 3. 23.

 

 

11. 상속

class.js

class Person {
  constructor(name, first, second) {
    this.name = name;
    this.first = first;
    this.second = second;
  }
  sum() {
    return this.first + this.second;
  }
}

class PersonPlus extends Person {
  avg() {
    return (this.first + this.second) / 2;
  }
}

let kim = new PersonPlus("kim", 10, 20);
console.log(`kim.sum() ${kim.sum()}`);
console.log(`kim.avg() ${kim.avg()}`);

  • extends 상속
    • 기능의 중복을 제거해줌
    • Person 클래스에 있는 sum() 부분을 PersonPlus가 상속 받음
    • Person은 부모 클래스, PersonPlus는 자식 클래스

 

 

 

12. super

class Person {
  constructor(name, first, second) {
    this.name = name;
    this.first = first;
    this.second = second;
  }
  sum() {
    return this.first + this.second;
  }
}

class PersonPlus extends Person {
  constructor(name, first, second, third) {
    super(name, first, second);
    this.third = third;
  }
  sum() {
    return super.sum() + this.third;
  }
  avg() {
    return (super.sum() + this.third) / 3;
  }
}

let kim = new PersonPlus("kim", 10, 20, 30);
console.log(`kim.sum() ${kim.sum()}`);
console.log(`kim.avg() ${kim.avg()}`);

  • super을 이용하면 부모 클래스가 가지고 있는 기능을 실행할 수 있음
  • super의 용법에는 두 가지가 있음
    1. 부모 클래스의 생성자 호출 super()
    2. 부모 클래스 super.sum()

 

 

 

13-1 object_inheritance

  • 객체를 만들어내는 공장, 설계도라고 할 수 있는 => class
  • 클래스를 통해 만들어진 구체적인 객체 => object (instance)

 

  • super object가 있고 이 객체의 기능을 상속 받으면서 새로운 기능을 추가하고 싶은 usb object가 있음
  • sub object는 super object로부터 바로 상속 받을 수 있음
  • class가 상속을 받는 전통적인 방법과 달리 JS는 객체가 직접 다른 객체를 상속받을 수 있고, 얼마든지 상속 관계를 바꿀 수 있음
  • super object로부터 상속을 받고 있는 sub object가 다른 객체로부터 상속을 받고 싶다면 링크만 바꿔주면 됨
    • 이러한 링크를 prototype link라고 함
    • prototype link가 가리키는 객체를 prototype object라고 함

 

 

 

13-2 __proto__

prototype-inheritance.js

let superObj = { superVal: "super" };
let subObj = { subVal: "sub" };
subObj.__proto__ = superObj;
console.log("subObj.subVal =>", subObj.subVal);
console.log("subObj.superVal =>", subObj.superVal);
subObj.superVal = "sub";
console.log("superObj.superVal =>", superObj.superVal);

  • __ptoro__ 라는 ptorototype link를 통해 객체를 상속받을 수 있음
  • 객체의 속성을 바꿔도 __proto__의 속성은 바뀌지 않음

 

 

 

13-3 Object_create

  • Object.create()를 사용해 객체를 상속 받는 객체를 생성할 수 있음
  • 개발자 도구와 debugger 키워드를 사용해 자바스크립트 코드를 디버깅할 수 있음

prototype-inheritance.js

let superObj = { superVal: "super" };
// let subObj = { subVal: "sub" };
// subObj.__proto__ = superObj;
let subObj = Object.create(superObj);
subObj.subVal = "sub";
debugger; //디버거
console.log("subObj.subVal =>", subObj.subVal);
console.log("subObj.superVal =>", subObj.superVal);
subObj.superVal = "sub";
console.log("superObj.superVal =>", superObj.superVal);

  • object.create를 사용해서 객체를 상속하는 새로운 객체를 만들 수 있음
  • object.create의 인자로 부로모 지정할 객체를 넣어줌

 

 

 

13-4 객체상속의 사용

prototype-inheritance.js

let superObj = { superVal: "super" };
// let subObj = { subVal: "sub" };
// subObj.__proto__ = superObj;
let subObj = Object.create(superObj);
subObj.subVal = "sub";
// debugger; //디버거
console.log("subObj.subVal =>", subObj.subVal);
console.log("subObj.superVal =>", subObj.superVal);
subObj.superVal = "sub";
console.log("superObj.superVal =>", superObj.superVal);

let kim = {
  name: "kim",
  first: 10,
  second: 20,
  sum: function () {
    return this.first + this.second;
  },
};

// let lee = {
//   name: "lee",
//   first: 10,
//   second: 10,
//   avg: function () {
//     return (this.first + this.second) / 2;
//   },
// };
// lee.__proto__ = kim;

let lee = Object.create(kim);
lee.name = "lee";
lee.first = 10;
lee.second = 10;
lee.avg = function () {
  return (this.first + this.second) / 2;
};

console.log("kim.sum() : ", kim.sum());
console.log("lee.sum() : ", lee.sum());
console.log("lee.avg() : ", lee.avg());

Object.create()의 사용을 권장함

 

 

 

14-1 객체와 함수

  • JS에서는 함수가 단독으로 쓰일 수도 있다
  • new가 앞에 있으면 객체를 만드는 생성자로 쓰일 수도 있음
  • call, bind 등 자유롭고 놀라운 사용법도 존재한다고 한다

 

 

 

14-2 call

  • JS의 모든 함수는 call이라는 method를 가짐
  • JS에서는 함수도 객체이기 때문
  • call 메소드의 인자로 객체를 지정하게 되면 해당 함수의 this는 인자로 받은 객체가 됨
  • call은 여러 parameter를 가질 수 있음
    1. 첫 번째 인자는 this로 지정할 객체가 옴
    2. 그 뒤로는 함수의 인자로 들어갈 값이 들어가게 됨

object_function.js

let kim = { name: "kim", first: 10, second: 20 };
let lee = { name: "lee", first: 10, second: 10 };
function sum(prefix) {
  return prefix + (this.first + this.second);
}
// sum();
console.log("sum.call(kim)", sum.call(kim, "=> "));
console.log("sum.call(lee)", sum.call(lee, ": "));

  • 내부적으로 this를 고정시키고 싶다면 bind를 사용함
  • bind는 호출한 함수를 변경하는 것이 아니라 인자로 받은 조건을 만족하는 새로운 함수를 리턴해줌

 

 

14-3 bind

let kim = { name: "kim", first: 10, second: 20 };
let lee = { name: "lee", first: 10, second: 10 };
function sum(prefix) {
  return prefix + (this.first + this.second);
}
// sum();
console.log("sum.call(kim)", sum.call(kim, "=> "));
console.log("sum.call(lee)", sum.call(lee, ": "));
//bind
let kimSum = sum.bind(kim, "-> ");
console.log("kimSum() ", kimSum());

 

 

 

15. prototype vs __proto__

function Person(){}
let Person = new Function();

함수는 JS에서는 객체다.

객체이기 때문에 property를 가질 수 있다.

 

function Person(name, first, second) {
  this.name = name;
  this.first = first;
  this.second = second;
}

Person.prototype.sum = function() {}

let kim = new Person('kim',10,20);

let lee = new Person('lee',10,20);

kim.sum();

  • Person이라는 함수를 생성하면 Person이라는 객체와 Person의 prototype 객체가 생성됨
  • Person 객체의 prototype은 Person의 Prototype 객체를 가리킴
  • Person의 prototype 객체도 Person에 속해있다는 것을 표시하기 위해서 constructor 프로퍼티에 Person 객체를 기록함. 서로 참조

 

https://developer.mozilla.org/ko/docs/Learn/JavaScript/Objects/Object_prototypes
https://developer.mozilla.org/ko/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

 

 

 

16-1 ~ 5생성자를 통한 상속 - 소개, 부모 생성자 실행, 부모와 연결하기, constructor 속성은 무엇인가, constructor 속성 바로잡기

constructor-inheritance.js

function Person(name, first, second) {
  this.name = name;
  this.first = first;
  this.second = second;
}

Person.prototype.sum = function () {
  return this.first + this.second;
};

function PersonPlus(name, first, second, third) {
  Person.call(this, name, first, second);
  this.third = third;
}

// PersonPlus.prototype.__proto__ = Person.prototype;
PersonPlus.prototype = Object.create(Person.prototype);
PersonPlus.prototype.constructor = PersonPlus;

PersonPlus.prototype.avg = function () {
  return (this.first + this.second + this.third) / 3;
};

let kim = new PersonPlus("kim", 10, 20, 30);
console.log(`kim.sum() ${kim.sum()}`);
console.log(`kim.avg() ${kim.avg()}`);
console.log(`kim.constructor ${kim.constructor}`);

 

 

 

 

 

 

부스트코스 [자바스크립트의 시작] 강의 공부 기록

 

 

 

300x250