JS중급_prototype의 특징

Adrian·2022년 3월 13일
0
post-thumbnail

▶️ prototype의 특징

  function Student(name, age) {
      this.name = name;
      this.age = 15;
  }

  Student.prototype.gender = 'woman';
  Student.prototype.weight = 45;

  var s1 = new Student("Kim");

  var arr = [1,2,3];
  var obj = {name : "jung"};

  console.log(Student.prototype);// {gender: 'woman', weight: 45, constructor: ƒ}
  console.log(arr.prototype); // undefined
  console.log(obj.prototype); // undefined
  • prototype은 constructor 함수에서만 생성된다. 일반 array, object를 만들면 해당 data 에는 prototype이 없다.
  • 일반 object를 상속하고 싶다면, 1.constructor함수를 만들고, 2.Object.create()를 쓰거나 3.class를 써야한다.

▶️ __proto__

  function Student(name, age) {
    this.name = name;
    this.age = 15;
}

  Student.prototype.gender = 'woman';

  var s1 = new Student("Kim");

  console.log(s1.__proto__);          // {gender: 'woman', constructor: ƒ}
  console.log(Student.prototype);     // {gender: 'woman', constructor: ƒ}
// 출력값이 동일하다. 
  • 부모에게 생성된 자식 object들은 '__proto__'라는 속성이 있다.
  • 자식.__proto__=부모의 유전자(constructor.prototype)라고 보면 된다.
  • 위 두 개의 console.log는 동일한 값이 출력된다.
  • 즉, '(__proto__ = 부모 prototype)을 의미한다.
    (__proto__ : 내 부모 유전자가 뭔지 유전자 검사를 하고 싶을 때 쓸 수 있는 속성)

▶️ __proto__ 를 직접 상속하기

  var parent = {name : 'Kim'};

  var child = {};

  child.__proto__ = parent; // child의 부모 유전자는 parent이다.
  console.log(child.name); // Park
  • (Child.proto = Parent;)를 통해 자식 object의 proto에 부모를 집어넣었다.
  • 이로인해 자식 object의 부모 유전자는 { name : 'Kim' } 이라는 object가 되었다.
  • 그래서 Child object가 Child.name 속성을 자유롭게 사용할 수 있는 것이다.
  • 자바스크립트에서 모든 function, object, array 등은 부모가 Object이다. 이들은 시스템 내부에서 new Object 로 생성된다고 보면 된다. 코드 내 모든 요소들의 아담과 이브같은 존재라고 보면 된다.

profile
관조, 사유, 끈기

0개의 댓글