Search code examples
javascriptprototype-programming

Why prototypes manually initialized to null still inherit from Object


If I write this

var o = Object.create(null)
alert(o instanceof Object) // this is false

How come this ends up being true

function o() {

}
o.prototype = null
alert(new o() instanceof Object) // this is true

Shouldn't manually setting the prototype to null cause it to inherit from nothing as Object.create does. Thanks in advance :-)


Solution

  • Briefly, if a constructor's prototype isn't an Object, then instances are given Object.prototype as their [[prototype]].

    The detail is in ECMA-262, §13.2.2 [[Construct]]:

    When the [[Construct]] internal method for a Function object F is called with a possibly empty list of arguments, the following steps are taken:

    1. Let obj be a newly created native ECMAScript object.
    2. Set all the internal methods of obj as specified in 8.12.
    3. Set the [[Class]] internal property of obj to "Object".
    4. Set the [[Extensible]] internal property of obj to true.
    5. Let proto be the value of calling the [[Get]] internal property of F with argument "prototype".
    6. If Type(proto) is Object, set the [[Prototype]] internal property of obj to proto.
    7. If Type(proto) is not Object, set the [[Prototype]] internal property of obj to the standard built-in Object prototype object as described in 15.2.4.
    8. Let result be the result of calling the [[Call]] internal property of F, providing obj as the this value and providing the argument list passed into [[Construct]] as args.
    9. If Type(result) is Object then return result.
    10. Return obj.

    Noting that in items 6 and 7, null is Type null (ECMA-262 §8.2), it is not the same as typeof null, which is object.