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
.
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
var a = {};
a.prototype = null;
alert(a.prototype);
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 :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.