在this回答时,我指示提问者不要在 Javascript 中覆盖原生的 Object
函数,因为我认为这会弄乱对象的创建过程。
但后来,我想了想,认为 所有 对象实际上都不太可能是使用此函数以及 new
关键字创建的。
例如,当使用字面量符号 (var a = {...}
) 创建对象时是否使用它?或者它只是执行 this = {}
?是否可以实际为 this
赋值?
我看到了this问题,这很相似,显然 Object
在没有 new
关键字的情况下使用时表现不同......该功能实际上是如何实现的?
最佳答案
您可以在 Chrome/V8 中覆盖对象,如果您这样做,就会发生不好的事情。输入以下内容会得到这些响应。
> Object
function Object() { [native code] }
> Number
function Number() { [native code] }
查看 Number.prototype 我们可以看到一整套方法和 Object 作为 Number 的原型(prototype):
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 的原型(prototype)有点不稳定:
Number.prototype
> Number
...empty...
由于 Object 是层次结构的根,如果将它重新分配给另一个对象,就会出现一些悖论。
关于javascript - 当与 "new"关键字一起使用时,Object 函数在 Javascript 中做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11596166/