반응형
1. Class
- 인스턴스 : 어떤 공통의 속성을 지니는 구체적인 대상
- 클래스 : 인스턴스들의 공통 속성을 모은 추상적인 개념
- 프로그램에서는 상위 클래스(superclass)가 정의되어야 하위 클래스(subclass)를 정의 가능.
2. Class
function Person(name, age) {
this._name = name;
this._age = age;
}
//static method
Person.getInformations = function(instance) {
return {
name : instance._name;
age : instance._age;
};
}
//(prototype) method
Person.prototype.getName = function() {
return this._name;
}
//(prototype) method
Person.prototype.getAge = function() {
return this._age;
}
var roy = new Person('로이', 30);
console.log(roy.getName()); //정상
console.log(roy.getAge()); //정상
console.log(roy.getInformations(roy)); //에러
console.log(Person.getInformations(roy)); //정상
2.1 static member
- 생성자 함수 객체에 직접 할당되어있는 프로퍼티
- 생성자 함수를 new 연산자 없이 함수(객체)로써 호출할 때 의미가 있는 값.
- 인스턴스에서 직접 접근 불가
- static method
- static properties
2.2 (prototype) methods
- 인스턴스에서 직접 접근 가능
3. Class Inheritance (클래스 상속)
3.1. superclass, subclass
- superclass : Person
- subclass : Employee
Employee.prototype = new Person(); Employee.prototype.constructor = Employee; //Employee의 prototype선언은 prototype을 덮어씌운 다음에 정의해야함 Employee.prototype.getPosition = function() { return this.position; }
3.2. bridge 추가
- Person(superclass)이 가지고 있는 인스턴스와의 연결관계를 끊고 싶을 때
- prototype chain 상의 불필요한 프로퍼티가 동작하지 않도록 함.
function Bridge(){}
Bridge.prototype = Person.prototype;
Employee.prototype = new Bridge();
Employee.prototype.constructor = Employee;
//Employee의 prototype선언은 prototype을 덮어씌운 다음에 정의해야함
Employee.prototype.getPosition = function() {
return this.position;
}
- 더글라스 크락포드 - 함수화 사용 추천
var extendClass = (function(){
function Bridge(){}
return function(Parent, Child) {
Bridge.prototype = Parent.prototype;
Child.prototype = new Bridge();
Chidl.prototype.constructor = Child;
}
})();
extendClass(Person, Employee);
//Employee의 prototype선언은 prototype을 덮어씌운 다음에 정의해야함
Employee.prototype.getPosition = function() {
return this.position;
}
- ES6 에서는 extends 가능
class Person {
constructor(name, age) {
this.name = name || '이름없음';
this.age = age || '이름없음';
}
getName() {
return this.name;
}
getAge() {
return this.age;
}
}
class Employee extends Person {
constructor(name, age, position) {
super(name, age);
this.position = position || '직책모름';
}
getPosition() {
return this.position;
}
}
반응형
'JavaScript +HTML5 + CSS3' 카테고리의 다른 글
[개념 정리] FRONT-END (0) | 2021.09.06 |
---|---|
[Core JavaScript] 6. prototype (0) | 2021.08.29 |
[Core JavaScript] 5. closure (0) | 2021.08.29 |
[Core JavaScript] 4. callback function (0) | 2021.08.29 |
[Core JavaScript] 3. this (0) | 2021.08.29 |