面试题答案
一键面试使用Object.isExtensible
检测对象可扩展能力
在JavaScript中,Object.isExtensible
方法用于判断一个对象是否是可扩展的(即是否可以添加新的属性)。语法如下:
const obj = {name: 'John'};
const isExtensible = Object.isExtensible(obj);
console.log(isExtensible);
上述代码直接调用Object.isExtensible
方法传入要检测的对象,返回true
表示对象可扩展,false
表示不可扩展。
模拟实现Object.isExtensible
以兼容不同浏览器
当浏览器不支持Object.isExtensible
方法时,可以通过以下方式模拟实现:
if (typeof Object.isExtensible!== 'function') {
Object.isExtensible = function (obj) {
if (typeof obj!=='object' || obj === null) {
throw new TypeError('The first argument must be an object');
}
const originalIsExtensible = Object.defineProperty(obj, '__proto__', {
value: null,
writable: true,
enumerable: false,
configurable: true
});
Object.defineProperty(obj, '__proto__', originalIsExtensible);
return originalIsExtensible.configurable;
};
}
这段代码首先检查Object.isExtensible
是否存在,如果不存在则定义一个模拟方法。该方法尝试通过操作对象的__proto__
属性来判断对象是否可扩展。如果能成功定义__proto__
属性,并且其configurable
为true
,则说明对象是可扩展的。最后恢复__proto__
属性原来的定义。