본문 바로가기
JavaScript

[JavaScript] 프로토타입

by eddypark 2023. 10. 13.

(1) 프로토타입 객체란

- JavaScript의 모든 객체는 자신의 부모 역할을 담당하는 객체와 연결되어 있는데 이러한 부모 객체를 prototype이라 한다.

- 생성자 함수에 의해 생성된 각 객체에 공유 프로퍼티를 제공하기 위해 사용한다.

- .prototype은 변수._proto_로 접근할 수 있다. 또한 변수.prototype은 함수만 가능하다.

var a = 22
console.log(a.__proto__ === Number.prototype);     // true
console.log(a.prototype === Number.prototype);     // false

function b(x) {
    this.x= x;
}
var c = new c ('test');
console.log(b.__proto__ === Function.prototype);   // true
console.log(b.prototype === c.__proto__);          // true

(2) constructor 프로퍼티

- 자신을 생성하는 객체를 가리킨다.

function a(x) {
  this.x = x;
}

var b = new a('test');

console.log(a.prototype.constructor === a);     // true   a() 생성자 함수에 의해 생성된 객체를 생성한 객체는 a() 생성자 함수이다.

console.log(b.constructor === a);               // true   b 객체를 생성한 객체는 a() 생성자 함수이다.

console.log(a.constructor === Function);        // true   a() 생성자 함수를 생성한 객체는 Function() 생성자 함수이다.

(3) Prototype chain

- 특정 객체의 프로퍼티나 메서드에 접근하려 할 때 존재하지 않는다면 자신의 부모 역할을 하는 프로토타입 객체의 프로토 타입이나 메서드를 차례대로 검색하는 것이다.

var information = {
  name: 'eddy',
  age: '26'
}

// Object.prototype.hasOwnProperty()
console.log(information.hasOwnProperty('name')); // true

- 함수의 프로토 타입 체인 (Object.prototype 객체를 프로토타입 체인 종점이라 한다.)

function Person(name, gender) {
  this.name = name;
  this.gender = gender;
  this.sayHello = function(){
    console.log('Hi! my name is ' + this.name);
  };
}

var foo = new Person('Lee', 'male');

console.log(foo .__proto__ === Person.prototype);                  // true
console.log(Person.prototype.__proto__ === Object.prototype);      // true
console.log(Person.prototype.constructor === information);         // true
console.log(Person.__proto__ === Function.prototype);              // true
console.log(Function.prototype.__proto__ === Object.prototype);    // true

- 프로토타입 객체도 property 추가 및 생성 가능하다. (즉시 반영된다.)

function a(name) {
    this.name = name;
}
var b = new a('eddy');
   
a.prototype.test= function(){                // 프로토타입 객체도 property 추가/삭제 가능
    console.log(this.name);
};
people.test();                                // eddy

- 원시타입의 확장

var str = 'test';
console.log(typeof str);                    // string
console.log(str.constructor === String);    // true
console.dir(str);                           // test

var strObj = new String('test');
console.log(typeof strObj);                 // object
console.log(strObj.constructor === String); // true
console.dir(strObj);                        // {0: "t", 1: "e", 2: "s", 3: "t", length: 4, __proto__: String, [[PrimitiveValue]]: "test" }

'JavaScript' 카테고리의 다른 글

[JavaScript] Strict mode  (0) 2023.10.16
[JavaScript] 스코프(Scope)  (0) 2023.10.16
[JavaScript] 함수  (1) 2023.10.12
[JavaScript] 객체 변경 불가성  (1) 2023.10.11
[JavaScript] 객체  (0) 2023.10.04