[Javascript] Understanding 'Prototype' of Javascript

Language/Typescript 2017.12.28 20:38

< 좋은 link >

< From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new >

The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.


When the code new Foo(...) is executed, the following things happen:

A new object is created, inheriting from Foo.prototype.
The constructor function Foo is called with the specified arguments, and with this bound to the newly created object. new Foo is equivalent to new Foo(), i.e. if no argument list is specified, Foo is called without arguments.
The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

< From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype >


    Specifies the function that creates an object's prototype.


즉, 'prototype' property는, 결국 'new' operation에서 object inherit을 위해 사용되는 reserved property이고, instance의 prototype chain은 [[Prototype]](de-facto __proto__) 에 의해 관리된다.

이상에서 다음을 알수(유추할수?) 있다.
- 'prototype' property 는 parent를 가리키는 일반적인 object 이다. (*1)
    : Default로, Function은 자기자신을 constructor로 가지는 prototype을 가진다.
- [[Prototype]]은 'prototype' object 를 가리킨다.

확실한 이해를 위해 'new' operation의 동작을 확인해 보자.(Tested on console of Chrome-63)

> function A(name) {
    this.date = Date.now();
    this.x = 'Proto';
    this.name = name;

> a = new A('a')
A {date: 1514262817152, x: "Proto", name: "a"}

> b = new A('b')            <= date 값이 매번 달라진다.
A {date: 1514262824795, x: "Proto", name: "b"}

> A.prototype                <= constructor만을 가지는 아주 단순한 object
{constructor: ƒ}
    constructor: ƒ A(name)
    __proto__: Object        <= Object Prototype

> c = Object.create(A.prototype);    <= 단순하게 constructor를 상속하는 과정이라고 생각할 수도 있다.
A {}

> c.constructor('c')            <= Prototype의 constructor를 새롭게 생성된 object에 binding해서 수행한다. (Same with, c.__proto__.constructor.call(c, 'c'))
undefined                   Note: binding of 'this' keyworkd (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
                       Note: c.__proto__.constructor('c') <= 잘못된 수행. prototype object 자체를 더럽히게 된다.
> c.constructor === c.__proto__.constructor

> c
A {date: 1514262907466, x: "Proto", name: "c"}

Trackbacks 0 : Comments 0