0

Recently I have been playing with javaScript prototype object and came across below example.

function Foo(){ 

}

Foo.prototype=null;

var fooObj=new Foo();

When I look at the fooObj from developer tools, the __proto__ property points to the global Object's prototype and I can access all properties and function defined in Object's prototype object. which should point to Foo function's prototype object, since I have assigned null to it I was expecting __proto__ will point to null, Pointing __proto__ might make more sense but I want to understand how value is assigned to __proto__ after object creation? what is causing it to point Object's prototype object?

I have seen many questions on prototype and proto but none of them solves my doubts.

georg
  • 211,518
  • 52
  • 313
  • 390
Akshay Naik
  • 669
  • 1
  • 6
  • 22
  • I suspect assigning the prototype property to `null` or `undefined` or indeed anything other than an object is treated as a special case. I know, for example, having user-land objects with a `null` `__proto__` was not possible until `Object.create` in ES5. – Ben Aston Aug 08 '17 at 10:55

1 Answers1

1

Full details in the specification*, but when you use a constructor function with null for its prototype property, new assigns Object.prototype (well, the default prototype for the realm; Object.prototype for our purposes) as the prototype of the new object.

I believe the only way to create an object with no prototype is Object.create(null).

You can set the prototype to null after creating the object via Object.setPrototypeOf, but in general it's best to avoid changing an object's prototype after you've created it.


* Specifically, it's tucked away in GetPrototypeFromConstructor, which says if the type of the constructor's prototype property isn't Object (for this purpose, null is of type Null, not type Object), use the default prototype for the realm.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875