How can I modify the Object constructor

When I run the following code

var ExtendedObject = function() {
  this.standard = 5;
};

Object = ExtendedObject.bind(Object);
var p = new Object();
console.dir(p.standard);

, the output is

5

as expected.

If I instead instantiate the variable p as an object literal like this:

var ExtendedObject = function() {
  this.standard = 5;
};

Object = ExtendedObject.bind(Object);
var p = {};
console.dir(p.standard);

The result is

undefined

I am trying to find a way to modify the constructor of Object such that I can add some standard content to all new objects being created.


No, it is absolutely impossible to redefine how an object literal evaluates; it will always become a native object with the builtin Object.prototype , not a subclass or anything and it will also not invoke a custom constructor.

This is in fact a security feature, as it prevents JSON hijacking.

… such that I can add some standard content to all new objects being created

That's a horrible idea and will break every library you'd ever use in this environment (including all functions you'd write yourself). However, if you insist on having a common (not individual!) property on all objects, you might consider defining it on Object.prototype . Not that I would recommend it, but at least do it correctly.


您可以创建一个类并从Object扩展它。

class MyObject extends Object {
  constructor() {
     super();
     this.standard = 5;
  }
}

const obj = new MyObject();
console.log(obj);

在Object的原型上定义属性,如下所示:

Object.defineProperty(Object.prototype, 'standard', {
  value: 5,
  writable: true,
  enumerable: true,
  configurable: true
});
var p = {};

console.dir(p.standard);
链接地址: http://www.djcxy.com/p/47786.html

上一篇: 我如何限制JSON访问?

下一篇: 我如何修改Object构造函数