컴퓨터 프로그램은 알고리즘의 모음이다.
Class = constructor(Properties/Attribute) + Methods/Behaviours
const Car = function () { const someInstance = {}; someInstance.position = 0; someInstance.move = function () { this.position++; } return someInstance; } let car1 = Car(); let car2 = Car(); car1.move(); console.log(car1); // {position: 1, move: ƒ} console.log(car2); // {position: 0, move: ƒ}
const extend = function(to, from) { for (let key in from) { to[key] = from[key] } }; const someMethods = {}; someMethods.move = function() { this.position++; }; const Car = function(position) { const someInstance = { position: position }; extend(someInstance, someMethods); return someInstance; } const car1 = Car(5); const car2 = Car(10); console.log(car1); // {position: 5, move: ƒ} console.log(car2); // {position: 10, move: ƒ}
const someMethods = {}; someMethods.move = function() { this.position++; }; const Car = function(position) { const someInstance = Object.create(someMethods); someInstance.position = position; return someInstance; } const car1 = Car(5); const car2 = Car(10);
const Car = function(position) { this.position = position; }; Car.prototype.move = function() { this.position++; }; const car1 = new Car(5); const car2 = new Car(10);
prototype
: 모델의 청사진을 만들 때 쓰는 원형 객체 (original form).constructor
: 생성자instantiation
: 인스턴스를 생성하는 과정.__proto__
: prototype chain다른 메소드를 상속받고 싶은 메소드에 상속해줄 메소드를 카피하여 할당한다.
// pseudoclassical Child.prototype = Object.create(Parent.prototype);
constructor는 원래 인스턴스가 가져야할(원하는 목표로) constructor로 재할당해준다.
→ 1번에서 메소드를 재할당해서 부모 constructor로 바뀐상태이기 때문에 원래의 자식 constructor로 할당해주는 단계
// pseudoclassical Child.prototype.constructor = Child; Child.prototype.someMethod = function() {} // 메소드 생성 // ES6 class : extends 키워드 사용 // extends : prototype연결 & constructor연결 한번에 해결 class Child extends Parent { }
부모 constructor에서도 상속받아야 되기 때문에 2번에서 연결한 constructor에 call / apply를 사용하여 this값을 넣어 상속받는다.
→ this값을 넣지 않는 경우 부모 constructor의 this 값은 undefined가 된다.
// pseudoclassical const Child = function (name) { Parent.call(this, name); // Parent.apply(this, arguments); } // ES6 class : super 키워드 사용 class Child extends Parent { constructor(name) { super(name); } }