2021년 1월 15일 TIL Inheritance

Class로 작성하는법

class Person {
  constructor() {
    (this.age = 12), (this.gender = "man");
  }
}
class Human extends Person {}

const per = new Person();
const hum = new Human();

console.log(hum.age);
console.log(hum.gender);

Persudo로 작성하는법

Person.prototype.face = function () {
  return "hello";
};

const Human = function () {
  Person.call(this, per.age);
};
Human.prototype = Object.create(Person.prototype);
Human.prototype.constructor = Human;
--> classextends의 역할과 비슷하다.

console.log(Human.prototype);

const per = new Person();
per.fat = "150kg"
person.prototype ===per.__proto_
-> new로 인해서 생겼다.
*** 중요한 개념 ***
  *** 이전에 개발해놓았던것이 엄청난 데이터가 
  proto로 되어있으므로 그전에 있던것도 배운다***

const hum = new Human();

hum.age;
console.log(hum.age);

extend

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/create

참고할만한 사이트

https://poiemaweb.com/js-prototype

super

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/super

상속과 prototype

https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain


function Person(name) {
    this.name = name;
}
function Student(name) {
    this.name=name;
}

Student.prototype=Person.prototype;
Student.prototype.hello = function() {
console.log("hello, world");
}
ƒ () {
console.log("hello, world");
}
const human = new Person();

human.hello()
hello, world
function Person(name) {
    this.name = name;
}
undefined
function Student(name) {
    
   this.name=name;}
undefined
Student.prototype=Person.prototype;
Student.prototype.hello = function() {
console.log("hello, world");
}
ƒ () {
console.log("hello, world");
}
const human = new Person();
undefined
human.hello()
VM505:3 hello, world
undefined
function Person(name) {
    this.name = name;
}
undefined
function Student(name,age) {
Person.call(this, name);
this.age= age;
}
undefined
function CoolStudent (name,age,hairColor) {
 Student.apply(this, [name,age]);
this.hairColor =hairColor
}
undefined
Student.prototype =Object.create(Person.prototype);
Person {}
Student.prototype.constructor = Student;
ƒ Student(name,age) {
Person.call(this, name);
this.age= age;
}
CoolStudent.prototype =Object.create(Student.prototype);
Student {}
CoolStudent.prototype.constructor = CoolStudent;
ƒ CoolStudent (name,age,hairColor) {
 Student.apply(this, [name,age]);
this.hairColor =hairColor
}
const human_1 = new Person('walli');
const human_2 = new Student ('kali',26);
const human_3 = new CoolStudent('moli',20,'pink');
undefined
console.log(human_2.name)
console.log(humans_3.age);
console.log(human_2.hairColor)

__proto__ <--객체에서 접근, prototype <-- 생성자함수에서 접근

좋은 웹페이지 즐겨찾기