Skip to content
Advertisement

What happened inside if assign a primitive type value to a function’s prototype?

let ill = function() { this.a = 'legal'; };
ill.prototype = 1234;

let ins = new ill();

console.log(Object.getPrototypeOf(ins) === ill.prototype);

It prints false.

What happened inside if I insist to assign a depreciated type to function’s prototype property?

Advertisement

Answer

let ill = function() { this.a = 'legal'; };
ill.prototype = 1234;

let ins = new ill();

console.log(Object.getPrototypeOf(ins) === Object.prototype); //true

When calling a function with new, as part of the call an object is created and its prototype will be automatically set.

Normally, this would be the prototype property of the constructor but not necessarily. When the prototype property is not an object, then Object.prototype is used instead.


The details are found in the specification, section 10.1.14 GetPrototypeFromConstructor:

10.1.14 GetPrototypeFromConstructor ( constructor, intrinsicDefaultProto )

The abstract operation GetPrototypeFromConstructor takes arguments constructor (a function object) and intrinsicDefaultProto (a String) and returns either a normal completion containing an Object or an abrupt completion. It determines the [[Prototype]] value that should be used to create an object corresponding to a specific constructor. The value is retrieved from the constructor’s “prototype” property, if it exists. Otherwise the intrinsic named by intrinsicDefaultProto is used for [[Prototype]]. It performs the following steps when called:

  1. Assert: intrinsicDefaultProto is this specification’s name of an intrinsic object. The corresponding object must be an intrinsic that is intended to be used as the [[Prototype]] value of an object.

  2. Let proto be ? Get(constructor, “prototype“).

  3. If Type(proto) is not Object, then

    a. Let realm be ? GetFunctionRealm(constructor).

    b. Set proto to realm‘s intrinsic object named intrinsicDefaultProto.

  4. Return proto.

In particular it is part of step 3. – the prototype if ill is not an object but a primitive, therefore, the intrinsic default prototype is used and that is set as "%Object.prototype%" as defined in section 10.2.2 [[Construct]] which defines the semantics of calling a function as a constructor:

10.2.2 [[Construct]] ( argumentsList, newTarget )

The [[Construct]] internal method of an ECMAScript function object F takes arguments argumentsList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. Let callerContext be the running execution context.

  2. Let kind be F.[[ConstructorKind]].

  3. If kind is base, then

    a. Let thisArgument be ? OrdinaryCreateFromConstructor(newTarget, “%Object.prototype%“).

[…]

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement