3

I need to find a way to create a JavaScript object with null prototype.

I'm not allowed to use the Object.create function.

I tried instantiating a constructor like new Constructor(), but the returned object always has a non-null prototype, even if Constructor.prototype === null.

1

3 Answers 3

3

Such an object already exists, it's Object.prototype, so your code is as simple as

x = Object.prototype

but you cannot create a new object like this, because new always sets the proto to an object:

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. @ http://ecma-international.org/ecma-262/5.1/#sec-13.2.2

You can manipulate __proto__ directly

a = {}
a.__proto__ = null
Sign up to request clarification or add additional context in comments.

Comments

1
var a = {};
a.prototype = null;
alert(a.prototype);

Comments

0

The usual way to create an object that inherits from another without Object.create is instantiating a function with the desired prototype. However, as you say it won't work with null:

function Null() {}
Null.prototype = null;
var object = new Null();
console.log(Object.getPrototypeOf(object) === null); // false :(

But luckily, ECMAScript 6 introduces classes. The approach above won't directly work neither because the prototype property of an ES6 class is non-configurable and non-writable.

However, you can take advantage of the fact that ES6 classes can extend null. Then, instead of instantiating, just get the prototype of the class:

var object = (class extends null {}).prototype;
delete object.constructor;
console.log(Object.getPrototypeOf(object) === null); // true :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.