我需要找到一种方法来创建一个具有null
原型的JavaScript对象。
我不能使用Object.create
函数。
我尝试通过实例化构造函数如new Constructor()
,但返回的对象总是具有非null
原型,即使Constructor.prototype === null
。
我需要找到一种方法来创建一个具有null
原型的JavaScript对象。
我不能使用Object.create
函数。
我尝试通过实例化构造函数如new Constructor()
,但返回的对象总是具有非null
原型,即使Constructor.prototype === null
。
这样的一个对象已经存在,它就是 Object.prototype
,所以你的代码可以非常简单:
x = Object.prototype
new
总是将proto设置为一个对象:
你可以直接操作如果Type(proto)不是Object,则根据15.2.4中描述的将obj的[[Prototype]]内部属性设置为标准内置对象原型对象。@ http://ecma-international.org/ecma-262/5.1/#sec-13.2.2
__proto__
。a = {}
a.__proto__ = null
var a = {};
a.prototype = null;
alert(a.prototype);
Object.create
。然而,正如您所说,这种方法在使用null
时无法工作:
function Null() {}
Null.prototype = null;
var object = new Null();
console.log(Object.getPrototypeOf(object) === null); // false :(
幸运的是,ECMAScript 6引入了类。上述方法也不会直接奏效,因为ES6类的prototype
属性是不可配置和不可写的。
然而,您可以利用ES6类可以扩展null
的事实。然后,不是实例化,只需获取类的prototype
即可:
var object = (class extends null {}).prototype;
delete object.constructor;
console.log(Object.getPrototypeOf(object) === null); // true :)