ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JS]Prototype
    JavaScript 2018. 1. 20. 16:46

    Prototype


    모든 객체는 자신의 프로토타입을 가리키는 [[Prototype]]라는 숨겨진 프로퍼티가 있다.

    [[Prototype]]와 __proto__는 같은 개념이다.


    함수 객체는 prototype 프로퍼티도 소유하게 된다.

    여기서 prototype과 [[Prototype]]는 모두 프로토타입 객체를 가리키지만 관점의 차이가 있다.



    [[Prototype]] / __proto__는 객체 입장에서 자신의 부모 역할을 하는 프로토타입을 가리킨다.


    prototype 은 함수 객체만 가지고 있는 프로퍼티다.

    함수 객체가 new 연산자를 통해 생성자 함수로 사용될 경우,

    새로 생성될 객체의 부모 역할을 하는 객체(프로토타입 객체)를 가리킨다.




    Constructor


    프로토타입 객체는 constructor 프로퍼티를 소유하게 된다.

    constructor 프로퍼티는 객체의 입장에서 자신을 생성한 객체를 가리키게 된다.


    ex.1)

    var CommonCtrl = function(name) {

        this.name = name;

    };


    CommonCtrl.prototype = {

        age : '31'

    };


    var _commonctrl = new CommonCtrl('Kim');


    console.dir(CommonCtrl.prototype.constructor === Object); // True

    console.dir(_commonctrl.constructor === Object); // True - 생성자 함수 객체 CommonCtrl의 new 연산자로 만들어 졌지만, CommonCtrl.prototype라는 Object 객체가 등장했기 때문에 이 녀석을 가리키게 된다.


    console.dir(CommonCtrl.constructor === Function); // Ture - 함수 객체는 Function.prototype을 바라본다.



    ex.2)

    var CommonCtrl = function(name) {

        this.name = name;

    };


    var _commonctrl = new CommonCtrl('Kim');


    console.dir(CommonCtrl.prototype.constructor === CommonCtrl); // True

    console.dir(_commonctrl.constructor === CommonCtrl); // True - 자신을 생성한 함수객체를 가리킨다.

    console.dir(CommonCtrl.constructor === Function); // Ture - 함수 객체는 Function.prototype을 바라본다.







    - 프로토타입 체인의 종점은 Object.prototype 다.

    댓글

Designed by Tistory.