[TIL] 211005

Lee Syong·2021년 10월 5일
0

TIL

목록 보기
48/204
post-thumbnail

📝 오늘 한 것

  1. 프로토타입 / 프로토타입 체인 / 표준 내장 객체의 확장

📚 배운 것

1. 프로토타입

1) 프로토타입(prototype)이란?

이거보고 prototype 이해 못하면 강의접음 참고

  • '유전자'라고 이해할 것

  • 부모 Me는 name = 'syong'을 가짐. 부모 Me에 의해 태어난 자식 I도 name = 'syong'임.

// 프로토타입
function Me () {
  this.a = 'a';
  this.b = 'b';
}

Me.prototype.name = 'syong';

const I = new Me();

console.log(I); // {a = 'a', b = 'b'}
console.log(I.name); // syong

2) 프로토타입 체인

생활코딩 2014 prototype 강의 참고

prototype에 저장된 속성들은
생성자를 통해서 객체가 만들어질 때
그 객체에 연결된다.

[ 예제 1 ]

function Ultra () {}
Ultra.prototype.ultraProp = true;

function Super () {}
Super.prototype = new Ultra();

function Sub () {}
Sub.prototype = new Super();
Sub.prototype.ultraProp = 2;

var o = new Sub();
console.log(o.ultraProp); // 2
  • 자바스크립트는 o.ultraProp의 값을 찞기 위해 먼저 객체 o뼟 뒤진다. 몝 찾으면 객체 o뼟 만든 생성자 Sub의 prototype 객체를 뒤진다. 생성자 Sub의 prototype 객체에서 ultraProp 프로퍼티를 발견하고 ꡸ 값을 출력한다.

[ 예제2 ]

function Ultra () {}
Ultra.prototype.ultraProp = true;

function Super () {}
Super.prototype = new Ultra();

function Sub () {}
var s = new Super();
s.ultraProp = 3;
Sub.prototype = s;

var o = new Sub();
console.log(o.ultraProp); // 3
  • 자바스크립트는 o.ultraProp의 값을 찞기 위해 먼저 객체 o뼟 뒤진다. 몝 찾으면 객체 o뼟 만든 생성자 Sub의 prototype 객체를 뒤진다. 생성자 Sub의 prototype 객체에 변수 s가 할당되어 있다. 변수 s에는 생성자 Super가 만든 객체가 할당되어 있다. ꡸ 객체의 prototype 프로퍼티가 3이므로 이를 출력한다.

[ 예제3 ]

function Ultra () {}
Ultra.prototype.ultraProp = true;

function Super () {}
var t = new Ultra();
t.ultraProp = 4;
Super.prototype = t;

function Sub () {}
var s = new Super();
Sub.prototype = s;

var o = new Sub();
console.log(o.ultraProp); // 4
  • 자바스크립트는 o.ultraProp의 값을 찞기 위해 먼저 객체 o뼟 뒤진다. 몝 찾으면 객체 o뼟 만든 생성자 Sub의 prototype 객체를 뒤진다. 여기서도 몝 찾으면 생성자 Super의 prototype 객체를 뒤진다. 위와 같은 과정을 깰쳐 4뼟 출력한다.

💡 주의 !

Sub.prototype = new Super(); // (o)
Sub.prototype = Super.prototype; // (x)

두 번째처럼 작성하면, Sub의 prototype 객체에 어떤 프로퍼티를 추가할 때 Super의 prototype 객체도 영향을 받게 된다. 즉, 자식 객체에 어떠한 기능을 추가하면 부모 객체에도 같은 기능이 추가되어 문제가 발생할 수 있다.


2. 표준 내장 객체의 확장

1) 표준 내장 객체(standard built-in object)란?

  • 자바스크립트나 자바스크립트가 동작하는 호스트 환경이, 개발자들에게 기본적으로 제공하는, 미댏 만들어져 있는 객체

  • Object, Function, Array, String, Boolean, Number, Math, Date, RegExp(정규표현식)

2) 사용자 정의 객체

  • 사용자가 직접 필요한 프로퍼티와 메서드를 정의해서 사용하는 객체

3) 표준 내장 객체를 확장하는 법

// 예제1 - 배열 요소 랜덤하게 가져오기
{
const arr = new Array('I', 'my', 'me', 'mine');

function getRandomValueFromArray () {
  const index = Math.floor(arr.length * Math.random());
  return arr[index];
}

console.log(getRandomValueFromArray());
}

// 예제1 - 표준 내장 객체의 확장
Array.prototype.random = function () {
  const index = Math.floor(this.length * Math.random());
  return this[index];
}

const arr = new Array('I', 'my', 'me', 'mine');
console.log(arr.random());
  • prototype을 이용해 모든 배열에 공통적으로 쓸 수 있는 API뼟 사용자가 직접 정의할 수 있다.

  • Array 생성자 함수로 만든 모든 배열 객체에 random() 메서드를 사용할 수 있도록, 함수에서는 arr 대신 this라고 써줘야 한다.


✨ 내일 할 것

  1. Object, 모듈
profile
능동적으로 살자, 행복하게😁

0개의 댓글