Object.isExtensible()

Object.isExtensible() 静态方法确定对象是否可扩展(是否可以添加新属性)。

¥The Object.isExtensible() static method determines if an object is extensible (whether it can have new properties added to it).

Try it

语法

¥Syntax

js
Object.isExtensible(obj)

参数

¥Parameters

obj

应检查的对象。

返回值

¥Return value

Boolean 指示给定对象是否可扩展。

¥A Boolean indicating whether or not the given object is extensible.

描述

¥Description

对象默认是可扩展的:它们可以添加新属性,并且可以重新分配它们的 [[Prototype]]。可以使用 Object.preventExtensions()Object.seal()Object.freeze()Reflect.preventExtensions() 之一将对象标记为不可扩展。

¥Objects are extensible by default: they can have new properties added to them, and their [[Prototype]] can be re-assigned. An object can be marked as non-extensible using one of Object.preventExtensions(), Object.seal(), Object.freeze(), or Reflect.preventExtensions().

示例

¥Examples

使用 Object.isExtensible

¥Using Object.isExtensible

js
// New objects are extensible.
const empty = {};
Object.isExtensible(empty); // true

// They can be made un-extensible
Object.preventExtensions(empty);
Object.isExtensible(empty); // false

// Sealed objects are by definition non-extensible.
const sealed = Object.seal({});
Object.isExtensible(sealed); // false

// Frozen objects are also by definition non-extensible.
const frozen = Object.freeze({});
Object.isExtensible(frozen); // false

非对象论证

¥Non-object argument

在 ES5 中,如果该方法的参数不是对象(原语),那么它将导致 TypeError。在 ES2015 中,如果传递非对象参数,它将返回 false,不会出现任何错误,因为根据定义,原语是不可变的。

¥In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError. In ES2015, it will return false without any errors if a non-object argument is passed, since primitives are, by definition, immutable.

js
Object.isExtensible(1);
// TypeError: 1 is not an object (ES5 code)

Object.isExtensible(1);
// false                         (ES2015 code)

规范

Specification
ECMAScript Language Specification
# sec-object.isextensible

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看