Search code examples
javascriptinheritanceconstructorprototype

Why I cannot create a pure object via a function-constructor in Javascript?


I've got a question about a Javascript inheritance. I wanna create a pure object. I can do it using a Object.create(null). But I decided to create it via a constructor function.

let User = function () {};

User.prototype = null;

So now I can expect, that every object created with new User() syntax, will have no prototype whatsoever. But

let user = new User();

console.log(user.__proto__ == Object.prototype); //true

Why it's not null here? Why it's not pure here? I think I'm missing something important.


Solution

  • Now I can expect, that every object created with new User() syntax, will have no prototype whatsoever.

    Yeah, that's a reasonable expectation, but JS doesn't work like that. The new operator falls back to creating an object from Object.prototype if the constructor's .prototype is not an object. Only ES5 introduced a way to create pure objects inheriting from null with Object.create.