part. 13 Prototype

Angelo·2020년 5월 7일
0

Codestates PRE Javascript

목록 보기
13/15
post-thumbnail

1. Prototype

Oasis - Don't Look Back In Anger

  • 자바스크립트 언어는 동적인 언어이고 클래스가 없다. 프로토타입 기반의 언어
  • 인스턴스가 생성 (instantiation) 될 때 원형(original form), 즉 프로토타입의 모양대로 인스턴스가 생성
  • 인스턴스의 메소드는 Object.prototype.something 으로 표현
**예시**
function Car(brand, name, color) { // Car 는 class 
  this.brand = brand; // this 객체 : 이 예제에서는 avante === this
  this.name = name;
  this.color = color;
} // constructor(생성자) 함수

Car.prototype.drive = function() { // prototype 객체 : 속성이나 메소드 정의 가능
  console.log(this.name + '가 운전을 시작합니다') 
};

let avante = new Car("hyundai", "avante", "black"); // avante === instance
avante.color; // 'black'
avante.drive(); // 'avante가 운전을 시작합니다'
  • prototype : 모델의 블루프린트를 만들 때 쓰는 원형 객체
  • constructor : 인스턴스가 초기화될 때 실행하는 생성자 함수
  • this : 함수가 실행될 때, 해당 scope마다 생성되는 고유한 실행 context(excution context). new 키워드로 인스턴스를 생성했을 때에는 해당 인스턴스가 바로 this의 값이 된다.

Inheritance

  • 상속이란, 상위 객체의 특징을 하위 객체에 넘겨주는것을 의미함
  • 자식객체는 부모객체의 기능을 base로 추가 수정 가능
**Array를 이용한 예시**
  
var Animal = function(name) {
  this.name = name;
}

Animal.prototype.sleep = function() {};

var dalmatian = new Animal('dalmatian');
dalmatian.toString(); // [object Object]

2. Prototype Chain

proto는 모든 객체에 포함되어 있기 때문에 상위의 프토토타입 체인을 확인한다

_ _ Proto _ _

(프로토타입 체인) (참조만 하는 기능)
Object에 대한 프로토타입의 toSring이 정의 되어 있어 따로 변수를 설정 안해줘도 됨
모든 객체는 최상위 상단에 위치하고 있는 Object를 상속받는다.

ex ) Object 에서 상속받은 EventTarget, EventTarget에서 상속받은 Node, Node에서 상속받은 Element, --상속받은 HTMLElement, --상속받은 HTMLLIElement

Assignable prototype

**할당이 가능, 예를 들어 배열의 특징을 가지고 있는 새로운것을 만들고 싶을때,
만든 프로토타입에 array프로토 타입을 입력하면 가능 **

var MyArray = function() {
}

MyArray.prototype = Array.prototype;

var my arr = new MyArray();
// myarr.push(1); // MyArray[1]

Object.create(proto)

첫번째 인자로 들어가는 프로토타입 객체를 기반으로 프로토타입을 만든다.
(프로토타입을 copy하는 개념)

**prototype 이용한 예시 1**
  
var Animal = function(name) {
  this.name = name;
}

Animal.prototype.sleep = function() {
  console.log(this.name +'is sleeping...');
};

var dalmatian = new Animal('dalmatian');

var Dog = function(name) {
  Animal.call(this, name); 
}
//new 키워드를 쓰면 인스턴스가 this가 되는데, 인스턴스가 Animal의 this까지 가지를 못함. 
//올려주려면 Animal.call(this,name)
//or Animal.apply(this, arguments)

Dog.prototype = Object.create(Animal.prototype); 
//Dog 프로토타입이 Animal 프로토타입을 copy
Dog.prototype.constructor = Dog; 
// 카피한 프로토타입의 constructor가 Animal을
// 바라보고 있기때문에 Dog로 바꿔 줘야함
Dog.prototype.learn = function () {
	console.log('배우는중...')
};

var pug = new Dog('pug');
pug.learn(); // 배우는중...
pug.sleep(); // pug is sleeping

3. class keyword

class 키워드를 이용해 상속하는 새로운 방법!

**class 키워드 이용한 예시 1**
  
class Animal {
  constructor(name) {
    this.name = name;
  }
  sleep() {
    console.log(this.name +'is sleeping...');
  }
}

var dalmatian = new Animal('dalmatian');

class Dog extends Animal { // 프로토타입 연결, 컨스트럭터 연결을 extends로 가능
  constructor(name) { // 첫번째 argument랑 같으면 constructor와 super 생략 가능
    super(name); // this 전달을 super로 가능 
  }
  learn() {
    console.log('배우는중...');
  }
}

var pug = new Dog('pug');
pug.learn(); // 배우는중...
pug.sleep(); // pug is sleeping
dalmatian.sleep(); // dalmatian is sleeping
**class 키워드 이용한 예시 2**
  
  class Animal {
    constructor(name) {
      this.name = name;
    }
    sleep() {
      console.log('zzz')
    }
  }

var dalmatian = new Animal('dalmatian');

class Dog extends Animal { // 프로토타입 연결
  sleep() { // 첫번째 argument와 같으므로 constructor 생략
    super.sleep; // this 전달을 super로 
  }
  sleep() {
    console.log('졸리다');
  }
}
  var pug = new Dog('pug');
pug.sleep(); // 졸리다
dalmatian.sleep(); // zzz
profile
나만의 학습 노트

0개의 댓글