Javascript ---对象 检测属性

目录

目录

in    

hasOwnProperty()

propertyIsEnumerable()

instanceof


检测属性:

检测一个属性是否属于某个对象。常用的方式主要有3种:

in    

hasOwnProperty()

propertyIsEnumerable()

instanceof

in (不是原型方法)

检测某属性是否是某对象的自有属性或者是继承属性

var obj = {
  name: 'zhangsan',
  age: 18,
  school: 'xx大学'
}
//in运算符的左侧为属性名称,右侧为对象
console.log('name' in obj); //true
console.log('age' in obj);  //true
console.log('gender' in obj); //false
//如果用in判断一个属性存在,这个属性不一定是obj的,它可能是obj继承得到的,如:
'toString' in obj;  //  true
因为toString定义在object对象中,而所有对象最终都会在原型链上指向object,所以obj也拥有toString属性。

Object.prototype.hasOwnProperty()

检测给定的属性是否是对象的自有属性,对于继承属性将返回false

var obj = {
  name: 'zhangsan',
  age: 18,
  school: 'xx大学'
}
console.log(obj.hasOwnProperty('name')); //true
console.log(obj.hasOwnProperty('age'));  //true
console.log(obj.hasOwnProperty('toString')); //false,toString为继承属性
console.log(obj.hasOwnProperty('gender')); //false

Object.prototype.propertyIsEnumerable()

propertyIsEnumerable()是hasOwnProperty()的增强版,除了是自身属性外,还要求是可枚举(可删除的)属性,即我们创建的属性。

var obj = {
  name: 'zhangsan',
  age: 18,
  school: 'xx大学'
}
console.log(obj.propertyIsEnumerable('name')); //true
console.log(obj.propertyIsEnumerable('age'));  //true
console.log(obj.propertyIsEnumerable('toString')); //false,不可枚举
console.log(obj.propertyIsEnumerable('gender')); //false

instanceof

instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。或者说判断一个对象是某个对象的实例。

// 自定义构造函数
function Person(name, age, gender) {
  this.name = name;
  this.age = age;
  this.gender = gender;
  this.sayName = function () {
    console.log(this.name);
  }
}

var person1 = new Person('zhangsan', 29, 'male');
var person2 = new Person('lisi', 19, 'female');

person1.sayName(); // zhangsan
person2.sayName(); // lisi


//instanceof 操作符的结果所示:
console.log(person1 instanceof Object); // true 
console.log(person1 instanceof Person); // true 
console.log(person2 instanceof Object); // true 
console.log(person2 instanceof Person); // true 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值