function Card(suit, rank) {
this.suit = suit;
this.rank = rank;
}
Card.prototype.show = function() {
console.log(this.suit + this.rank)
}
var Card = function(suit, rank) {
this.suit = suit;
this.rank = rank;
}
class Card {
constructor(suit, rank) {
this.suit = suit;
this.rank = rank;
}
show() {
console.log(this.suit + this.rank)
}
}
var Card = class {
constructor(suit, rank) {
this.suit = suit;
this.rank = rank;
}
show() {
console.log(this.suit + this.rank)
}
}
프로퍼티를 특정 방법으로만 읽고 쓰도록 강제할 수 있음.(getter, setter)
function Person(name) {
Object.defineProtperty(this, 'name', {
get : function() {
return name;
},
set : function(newName) {
name = newName;
},
configurable : true,
enumerable : true,
})
}
Person.prototype.sayName = function() {
console.log(this.name);
}
var person = new Person('Tom');
console.log(p.name); // Tom
p.name = 'Huck';
console.log(p.name); // Huck
p.sayName(); // Huck
자바스크립트에서는 생성자가 클래스의 역할을 함
객체의 프로토타입 상속 메커니즘을 채택
생성자 또한 객체이므로 객체의 프로토타입 상속을 활용하면 생성자 상속을 구현할 수 있음.
상속하는 생성자 : 슈퍼타입 생성자
상속받은 생성자 : 서브타입 생성자
Ellipse생성자로 생성한 인스턴스 ellipse는 자신이 갖고있지 않는 메서드를
Ellipse.prototype과 Object.prototype에서 상속받아 사용할 수 있음
function Circle(r) {
this.a = r;
this.b = r;
}
var circle = new Circle(2);
circle의 프로토타입 : Circle.prototype
Circle.prototype의 프로토타입 : Object.prototype
circle에서 Ellipse.prototype을 사용하려면 Circle.prototype이 Ellipse.prototype을 상속받아야함.
-> circle의 프로토타입체인에 Ellipse.prototype을 삽입해야함
예제2-다른방법
하지만 이 방법은 Circle.prototype에 이미 생성된 Ellipse의 프로퍼티를 낭비하는 단점이 있음.
call메서드를 이용해 Ellipse 생성자에서 정의한 프로퍼티(this.a, this.b)를 Circle생성자 안에 가져오기
Ellipse.prototype.toString을 덮어쓰는 방식으로, 새로정의하는것 대신에
Ellipse.prototype 메서드를 이용해서 정의함
클래스 구문의 종류
// 생성자
function Circle(center, radius) {
this.center = center;
this.radius = radius;
}
Circle.prototype.area = function() {
return Math.PI * this.radius * this.radius;
}
// 클래스 구문
class Circle2 {
constructor(center, radius) {
this.center = center;
this.radius = radius;
}
// prototype 메서드
area() {
return Math.PI * this.radius * this.radius;
}
}
클래스 선언문 작성 방법
class 이름
클래스선언문과 함수선언문의 차이
클래스 표현식
var Circle = class {
//생성자를 이용한 초기화
constructor(center, radius) {
this.center = center;
this.radius = radius;
}
area() {
return Math.PI * this.radius * this.radius;
}
}
class 다음에는 모든 식별자를 이름으로 사용할 수 있음
var Circle = class Kreis { ... }
// Kreis라는 이름은 클래스바디 내에서만 유효
var k = new Kreis() // 에러발생
var c = new Circle() // 정상적으로 인스턴스 생성됨
getter와 setter 생성하기
class Person {
constructor(name) {
this.name = name;
}
get name() {
return this._name;
}
set name(value) {
this._name = value;
}
sayName() {
console.log(this.name);
}
}
get과 set키워드를 사용해서 접근자를 정의
var person = new Person('Tom');
console.log(person.name); // 'Tom'
person.name = 'Huck';
console.log(person.name); // 'Huck'
person.sayName(); // Huck
static 메서드를 통해 정적메서드 작성 가능
extends 키워드를 클래스 선언문이나 표현식에 사용하면 다른 생성자를 상속받을 수 있음
Ball 생성자의 인스턴스가 Circle의 area와 toString이외에도 추가로 정의한 move도 사용할 수 있다.
super 키워드를 활용해 서브타입의 생성자가 슈퍼타입 생성자의 메서드를 호출할 수 있다.
**클래스구문은 함수를 정의한다(클래스를 정의하지 않는다)