Object() 构造函数
Object()
构造函数将输入转换为对象。其行为取决于输入的类型。
¥The Object()
constructor turns the input into an object. Its behavior depends on the input's type.
语法
¥Syntax
new Object()
new Object(value)
Object()
Object(value)
注意:
Object()
可以与new
一起调用,也可以不与new
一起调用,但有时效果不同。参见 返回值。¥Note:
Object()
can be called with or withoutnew
, but sometimes with different effects. See Return value.
参数
返回值
¥Return value
当 Object()
构造函数本身被调用或构造时,它的返回值是一个对象:
¥When the Object()
constructor itself is called or constructed, its return value is an object:
- 如果值为
null
或undefined
,它将创建并返回一个空对象。 - 如果该值已经是一个对象,则返回该值。
- 否则,它返回与给定值对应的类型的对象。例如,传递
BigInt
原语将返回BigInt
封装对象。
当 Object()
被构造但 new.target
不是 Object
构造函数本身时,行为略有不同 - 它初始化一个以 new.target.prototype
作为其原型的新对象。任何参数值都会被忽略。例如,当 Object()
在 延伸 Object
的类的构造函数中通过 super()
隐式调用时,可能会发生这种情况。在这种情况下,即使将数字传递给 super()
,构造函数内的 this
值也不会成为 Number
实例。
¥When Object()
is constructed but new.target
is not the Object
constructor itself, the behavior is slightly different — it initializes a new object with new.target.prototype
as its prototype. Any argument value is ignored. This may happen, for example, when Object()
is implicitly called via super()
in the constructor of a class that extends Object
. In this case, even if you pass a number to super()
, the this
value inside the constructor does not become a Number
instance.
示例
创建一个新对象
使用给定未定义和 null 类型的对象
获取 BigInt 和 Symbol 的封装对象
¥Obtaining wrapper objects for BigInt and Symbol
当使用 new
调用时,BigInt()
和 Symbol()
构造函数会抛出错误,以防止创建封装对象而不是原始值的常见错误。为这些类型创建封装对象的唯一方法是使用它们调用 Object()
:
¥The BigInt()
and Symbol()
constructors throw an error when called with new
, to prevent the common mistake of creating a wrapper object instead of the primitive value. The only way to create a wrapper object for these types is to call Object()
with them:
const numberObj = new Number(1);
console.log(typeof numberObj); // "object"
const bigintObj = Object(1n);
console.log(typeof bigintObj); // "object"
const symbolObj = Object(Symbol("foo"));
console.log(typeof symbolObj); // "object"
规范
Specification |
---|
ECMAScript Language Specification # sec-object-constructor |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also