객체지향 Javascript - newlife-js/Wiki GitHub Wiki

객체지향 Javascript

참고

생성자

function Person(name) {
  this.name = name;
  this.greeting = function() { ... }
}
// 함수는 밖에서 prototype으로 선언하기도 함.
Person.prototype.greeting = function() { ... };

var person1 = new Person('Bob');

객체 복사

var person2 = Object.create(person1);

상속

call 함수: 변수 상속 prototype 복사: 함수 상속

function Teacher(first, last, age, subject) {
  Person.call(this, first, last, age); // default constructor는 Person.call(this);
  this.subject = subject;
}

Teacher.prototype = Object.create(Person.prototype);
Teacher.prototype.constructor = Teacher;
Teacher.prototype.greeting = function() { ... };

class 스타일

class Person {
  constructor(first, last, age, gender, interests) {
    this.name = {
      first,
      last
    };
    this.age = age;
    this.gender = gender;
    this.interests = interests;
  }

  greeting() {
    console.log(`Hi! I'm ${this.name.first}`);
  };

  farewell() {
    console.log(`${this.name.first} has left the building. Bye for now!`);
  };
}

class Teacher extends Person {
  constructor(first, last, age, gender, interests, subject, grade) {
    super(first, last, age, gender, interests);
    // subject and grade are specific to Teacher
    this._subject = subject;
    this.grade = grade;
  }

  get subject() {
    return this._subject;
  }

  set subject(newSubject) {
    this._subject = newSubject;
  }
}

Class 특징

hoisting(define되기 전에는 사용x -> 맨 앞에 선언해야 함) 되지 않음.
덮어쓰기 안됨.