const arr = new Array
Array
가 일종의 클래스라고 한다면 Array의 prototype 객체 내부 요소들이 인스턴스에 상속된다고 할 수 있다.// 생성자
var Rectangle = function(width, height) {
this.width = width;
this.height = height;
};
// 프로토타입 메서드
Rectangle.prototype.getArea = function() {
return this.width * this.height;
}
// 스태틱 메서드
Rectangle.isRectangle = function(instance) {
return instance instanceof Rectangle && instance.width > 0 && instance.height > 0;
}
var rect1 = new Rectangle(3, 4)
console.log(rect1.getArea()); // 12
console.log(rect1.isRectangle(rect1)); // Type Error
console.log(Rectangle.isRectangle(rect1)); // true
클래스(prototype)이 구체적인 데이터를 지니지 않게 하는 방법 + subClass 인스턴스의 constructor가 superClass를 가리키는 것을 원래의 subClass를 바라보도록 하는 것
var extendClass1 = function(SuperClass, SubClass, subMethods) {
SubClass.prototype = new SuperClass();
for (var prop in Subclass.prototype) {
if (SubClass.prototype.hasOwnProperty(prop)) {
delete Subclass.prototype[prop];
}
}
SubClass.prototype.constructor = SubClass;
if (subMethods) {
for (var method in subMethods) {
SubClass.prototype[method] = subMethods[method];
}
}
Object.freeze(SubClass.prototype);
return SubClass;
}
var extendClass2 = (function() {
var Bridge = function() {};
return function(SuperClass, SubClass, subMethods) {
Bridge.prototype = superClass.prototype;
SubClass.prototype = new Bridge();
SubClass.prototype.constructor = SubClass;
if (subMethods) {
for (var method in subMethods) {
SubClass.prototype[method] = subMethods[method];
}
}
Object.freeze(SubClass.prototype);
return SubClass;
};
})();
var extendClass3 = function (SuperClass, SubClass, subMethods) {
SubClass.prototype = Object.create(SuperClass.prototype);
SubClass.prototype.constructor = SubClass;
if (subMethods) {
for (var method in subMethods) {
SubClass.prototype[method] = subMethod[method];
}
}
Object.freeze(SubClass.prototype);
return SubClass;
};
EX6에서 클래스 문법이 추가
var ES5 = function(name) {
this.name = name;
};
ES5.staticMethod = function() {
return this.name + ' staticMethod';
};
ES5.prototype.method = function() {
return this.name + ' method';
};
var es5Instance = new ES5('es5');
console.log(ES5.staticMethod());
console.log(es5Instance.method());
var ES6 = class {
constructor(name) {
this.name = name;
}
static staticMethod() {
return this.name + ' staticMethod';
}
method() {
return this.name + ' method';
}
};
var es6Instance = new ES6('es6');
console.log(ES6.staticMethod());
console.log(es6Instance.method());
var Rectangle = class {
constructor (width, height) {
this.width = width;
this.height = height;
}
getArea () {
return this.width * this.height;
}
};
var Square = class extends Rectangle {
constructor(width) {
super(width, width);
}
getArea() {
console.log('size is :', super.getArea());
}
}
코어자바스크립트를 다 읽었다.
처음에는 용어에 적응하느라 쉽사리 읽히 않았고 뒤로 가면 갈수록 바로 와닿는 내용은 아니라서 계속 읽었던 부분을 다시 읽고는 했다.
하지만 마지막 장을 읽었을 때의 뿌듯함이란!
이제 1회독을 했을 뿐이고 이제 막 자바스크립트의 내면을 살짝 본 느낌이다.
앞으로 자바스크립트를 계속 사용하면서 최소한 3회독은 해야지 이게 이 내용이었구나 하지 않을까 싶다. 빠른 시일 내에 책의 도움 없이 스스로 이와 같은 내용을 정리 할 수 있기를 바라며 다시 1장을 펼쳐봐야겠다.