javascript 属性检测

// 测试数据定义
let symbolKey = Symbol('symbolKey');
function Obj(){
    
    
	this.ownKey = 1;
	this[symbolKey] = 2;
}
Obj.prototype.prototypeKey = 3;
let o = new Obj();
Object.defineProperty(o, 'unenumerableKey', {
    
    
	enumerable: false,
	value: 4
})
  1. in 本地属性或继承属性

    'ownKey' in o;			// true
    symbolKey in o;			// true
    'prototypeKey' in o;	// true
    'unenumerableKey' in o;	// true
    'undefinedKey' in o;	// false 本地、原型链上都没有的属性
    'ownKey ' in o;			// false 错误的空格
    
  2. Object.prototype.hasOwnProperty() 本地属性

    o.hasOwnProperty('ownKey');			// true
    o.hasOwnProperty(symbolKey);		// true
    o.hasOwnProperty('prototypeKey');	// false 非本地属性
    o.hasOwnProperty('unenumerableKey');// true
    o.hasOwnProperty('undefinedKey');	// false 本地、原型链上都没有的属性
    o.hasOwnProperty('ownKey ');		// false 错误的空格
    
  3. Object.prototype.propertyIsEnumerable() 本地属性且可枚举属性

    o.propertyIsEnumerable('ownKey');			// true
    o.propertyIsEnumerable(symbolKey);			// true
    o.propertyIsEnumerable('prototypeKey');		// false 非本地属性
    o.propertyIsEnumerable('unenumerableKey');	// false 不可枚举属性
    o.propertyIsEnumerable('undefinedKey');		// false 本地、原型链上都没有的属性
    o.propertyIsEnumerable('ownKey ');			// false 错误的空格
    

注: Object.prototype.propertyIsEnumerable() 判断为true的属性不一定可以用 for...inObejct.keys(o) 枚举(例如:Symbol做键的本地属性)

猜你喜欢

转载自blog.csdn.net/SJ1551/article/details/109286161