Prototype

하태현·2020년 11월 14일
0

javascript

목록 보기
11/23
post-thumbnail

프로토타입 속성

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();

출처 : Object.create() - MDN

profile
왜?를 생각하며 개발하기, 다양한 프로젝트를 경험하는 것 또한 중요하지만 내가 사용하는 기술이 어떤 배경과 이유에서 만들어진 건지, 코드를 작성할 때에도 이게 최선의 방법인지를 끊임없이 질문하고 고민하자. 이 과정은 앞으로 개발자로 커리어를 쌓아 나갈 때 중요한 발판이 될 것이다.

1개의 댓글

comment-user-thumbnail
2021년 4월 14일

글 잘 읽고 갑니다 ^^~*

답글 달기