JavaScript 는 prototype 기반으로 inheritance를 구현하여 불필요한 중복을 제거하여 memory leak을 최소화 한다. 중복을 제거하는 방법은 기존의 코드를 적극적으로 reuse 하는 것이다.
아래의 코드는 자신의 상태를 나타내는 radius property 만 개별적으로 소유하고 내용이 동일한 method 는 inheritance 를 통해 공유하여 사용한다.
// ES5(use extends on ES6)
// Bad code
function Circle(radius) {
this.radius = radius;
this.getArea = function () {
return Math.PI = this.radius ** 2
};
}
const circle0 = new Circle(1);
const circle1 = new Circle(2); // getArea method created again! (memory leak)
console.log(circle0.getArea === circle1.getArea); //false
// Good Code
function Circle(radius) {
this.radius = radius;
}
Circle.prototype.getArea = function () {
return Math.PI * this.radius ** 2;
}
const circle0 = new Circle(1);
const circle1 = new Circle(2);
console.log(circle0.getArea === circle1.getArea); //true
자체적으로 value 를 갖지 않고 다른 field 의 value 를 읽거나 저장할 떄 호출되는 Accessor function 으로 구성된 property 다.
const mathCustom = {
_value: 1,
get multiple() {
return this._value;
},
set multiple(v0){
this._value *= v0;
}
}
console.log(mathCustom.multiple) // 1
mathCustom.multiple = 10;
console.log(mathCustom.multiple) // 10
mathCustom.multiple = 20;
console.log(mathCustom.multiple) // 200
class 는 hoisting 되어 function 으로 평가된다.
// ES5
var Person = (function () {
//constructor
function Person(name) {
this.name = name;
}
//prototype method
Person.prototype.sayHi = function () {
console.log(this.name);
}
//static method
Person.sayHello = function () {
console.log("hello");
}
return Person;
}())
// ES6
class Person {
constructor(name) {
this.name = name;
}
//prototype method
sayHi() {
console.log(this.name);
}
//static method
static sayHello() {
console.log("hello");
}
}