function add(a,b) {
return a + b;
}
function multiply(a,b) {
return a * b;
}
console.log(add.prototype); // 객체
console.log(multiply.prototype); // 객체
자바스크립트의 모든 함수에는
prototype
이라는 속성이 있다.
자바스크립트의 모든 인스턴스 객체는 해당 객체의 프로토타입에 존재하는 속성 및 메소드에 접근하여 사용할수 있다.
function Person(name) {
this.name = name;
}
Person.prototype.age = 28;
const hth = new Person("hth");
console.log(hth.age); // 28
Person
함수는 생성될때 고유의 프로토타입 객체(Person.prototype
)와 함께 생성된다.
hth
는 생성자 함수를 이용해 만들어졌기 때문에Person.prototype
에 존재하는 속성을 사용할수 있다.
function Person(name) {
this.name = name;
}
Person.prototype.age = 28;
const hth = new Person("hth");
console.log(hth); // 인스턴스(자식)
console.log(hth.__proto__); // __proto__(엄마가 누구냐?)
console.log(Person.prototype); // 엄마
console.log(hth.__proto__ === Person.prototype); // true
쉽게 정리하자면 아래와 같다.
hth
: Instance (자식)Person
: Constructor (아빠)Person.prototype
:__proto__
(엄마)
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.age = 300;
const hth = new Person("hth", 28);
console.log(hth.age); // 28
모든 자식은 엄마의 속성을 빌려 쓸수 있다. 그러나 무조건 빌리는게 아니고 자기 자신한테 없을때 빌려쓴다.
// Shape - 상위클래스
function Shape() {
this.x = 0;
this.y = 0;
}
// 상위클래스 메서드
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.info('Shape moved.');
};
// Rectangle - 하위클래스
function Rectangle() {
Shape.call(this); // super 생성자 호출.
}
// 하위클래스는 상위클래스를 확장
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
var rect = new Rectangle();
글 잘 읽고 갑니다 ^^~*