详谈js中isPrototypeOf()、hasOwnProperty()、propertyIsEnumerable()的区别。

isPrototypeOf()

isPrototypeOf是用来判断指定对象object1是否存在于另一个对象object2的原型链中,是则返回true,否则返回false。
格式如下:
  object1.isPrototypeOf(object2);
  object1是一个对象的实例;
  object2是另一个将要检查其原型链的对象。
原型链可以用来在同一个对象类型的不同实例之间共享功能。
如果 object2 的原型链中包含object1,那么 isPrototypeOf 方法返回 true。
如果 object2 不是一个对象或者 object1 没有出现在 object2 中的原型链中,isPrototypeOf 方法将返回 false。

示例:
本示例展示了 Baz.prototype, Bar.prototype, Foo.prototype 和 Object.prototype 在 baz 对象的原型链上:

function Foo() {}
function Bar() {}
function Baz() {}

Bar.prototype = Object.create(Foo.prototype);
Baz.prototype = Object.create(Bar.prototype);

var baz = new Baz();

console.log(Baz.prototype.isPrototypeOf(baz)); // true
console.log(Bar.prototype.isPrototypeOf(baz)); // true
console.log(Foo.prototype.isPrototypeOf(baz)); // true
console.log(Object.prototype.isPrototypeOf(baz)); // true

hasOwnProperty()

hasOwnProperty() 检查对象自身中是否含有该属性。使用该方法时,只有对象自身中含有属性时才会返回true。

格式如下:
object.hasOwnProperty(proName);
判断proName的名称是不是object对象的一个属性或对象。

var a = {
            x: 1
        };
        console.log(a.hasOwnProperty("x")); //true
        console.log(a.hasOwnProperty("y")); //false
        console.log(a.hasOwnProperty("toString")); //false toString是继承属性

propertyIsEnumerable()

propertyIsEnumerable()是hasOwnProperty()的增强版,只有检侧到是目有属性且这个属性的可枚举性(enumerable attribute)为true时它才返回true.某些内置属性是不可枚举的。通常由JavaScript代码创建的属性都是可枚举的。除非调用Object.defineProperty() 方法来修改。

propertyIsEnumerable() 方法返回一个布尔值,表示指定的属性是否可枚举。
语法

obj.propertyIsEnumerable(prop)

参数

prop
   需要测试的属性名。

返回值

用来表示指定的属性名是否可枚举的布尔值。

描述

每个对象都有一个 propertyIsEnumerable 方法。此方法可以确定对象中指定的属性是否可以被 for…in
循环枚举,但是通过原型链继承的属性除外。如果对象没有指定的属性,则此方法返回 false。

例子

const object1 = {};
const array1 = [];
object1.property1 = 42;
array1[0] = 42;

console.log(object1.propertyIsEnumerable('property1'));
// expected output: true

console.log(array1.propertyIsEnumerable(0));
// expected output: true

console.log(array1.propertyIsEnumerable('length'));
// expected output: false

下面的例子演示了用户自定义对象和内置对象上属性可枚举性的区别.

var a = ['is enumerable'];

a.propertyIsEnumerable(0);        // 返回 true
a.propertyIsEnumerable('length'); // 返回 false

Math.propertyIsEnumerable('random'); // 返回 false
this.propertyIsEnumerable('Math');   // 返回 false


愿你的坚持终有收获。

个人博客网站,,没事来逛逛



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值