Object函数在Javascript中与“;新的“;关键字

What does the Object function do in Javascript when used with the "new" keyword?

本文关键字:关键字 新的 中与 函数 Javascript Object      更新时间:2023-12-17

在这个答案中,我指示提问者不要覆盖Javascript中的原生Object函数,因为我认为它会打乱对象创建过程。

但后来,我思考了一下,发现所有对象实际上都不太可能使用这个函数和new关键字创建。

例如,当使用文字符号(var a = {...})创建对象时,是否使用它?或者它只是做this = {}?真的有可能给this赋值吗?

我看到了这个类似的问题,显然Object在没有new关键字的情况下使用时表现不同。。。该功能实际是如何实现的?

您可以在Chrome/V8中覆盖Object,如果这样做,就会发生不好的事情。键入以下内容会得到这些响应。

> Object
 function Object() { [native code] }
> Number
 function Number() { [native code] }

查看Number.prototype,我们可以看到一整套方法和Object作为Number的原型:

Number
constructor: function Number() { [native code] }
toExponential: function toExponential() { [native code] }
toFixed: function toFixed() { [native code] }
toLocaleString: function toLocaleString() { [native code] }
toPrecision: function toPrecision() { [native code] }
toString: function toString() { [native code] }
valueOf: function valueOf() { [native code] }
__proto__: Object
  __defineGetter__: function __defineGetter__() { [native code] }
  __defineSetter__: function __defineSetter__() { [native code] }
  __lookupGetter__: function __lookupGetter__() { [native code] }
  __lookupSetter__: function __lookupSetter__() { [native code] }
  constructor: function Object() { [native code] }
  hasOwnProperty: function hasOwnProperty() { [native code] }
  isPrototypeOf: function isPrototypeOf() { [native code] }
  propertyIsEnumerable: function propertyIsEnumerable() { [native code] }
  toLocaleString: function toLocaleString() { [native code] }
  toString: function toString() { [native code] }
  valueOf: function valueOf() { [native code] }

但是如果我们覆盖对象

Object = {}

Number的原型有点不稳定:

Number.prototype
   > Number
  ...empty...

由于Object是层次结构的根,如果将其重新分配给另一个对象,则会有点矛盾。

使用文字表示法得到的对象与使用函数表示法获得的对象相同。证明:

> ({}).__proto__ === new Object().__proto__
true
> new Object().__proto__ === Object.prototype
true

这意味着左侧和右侧的对象是从同一个原型创建的,即Object.prototype

Object函数是用来尝试将某个对象作为对象的,如果你不传递任何参数,它将构造一个null对象,因此它是一个空对象。

var a = new Object(); // a is {}
var b = new Object("1"); // b is an object which store 1 as a string.
/* 
  JS console says:
  String
    0: "1"
    length: 1
*/
var c = new Object(1); // c is an object which store 1 as an integer.
/* 
  JS console says:
  Number
  //There is no other property or method here.
*/

我在没有关键字的情况下尝试了它,但没有任何变化。所有对象都与上面的对象相同。

希望这能解决你的好奇心。