hasOwnProperty和isPrototypeOf

本文详细探讨了JavaScript中hasOwnProperty、isPrototypeOf及in操作的区别与联系,并通过具体示例对比了isPrototypeOf与instanceof的不同之处,帮助读者更好地理解JavaScript原型链的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

hasOwnProperty:是用来判断一个对象是否有你给出名称的属性或对象,此方法无法检查该对象的原型链中是否具有该属性,该属性必须是对象本身的一个成员。
isPrototypeOf是用来判断要检查其原型链的对象是否存在于指定对象实例中,是则返回true,否则返回false。
in 操作检查对象中是否有名为 property 的属性。也可以检查对象的原型,判断该属性是否为原型链的一部分.
hasOwnProperty:
var obj = {a:1,b:2}
obj.hasOwnProperty('a')

isPrototypeOf:
function F(){}
var fn = new F()
F.prototype.isPrototypeOf(fn)

[color=blue]

前者是判断对象中是否存在某个属性,后者是判断对象是否是原型链的对象。[/color]

那么isPrototypeO与instanceof又有什么区别?

function A () {
this.a = 1;
}
function B () {
this.b = 2;
}
B.prototype = new A();
B.prototype.constructor = B;

function C () {
this.c = 3;
}
C.prototype = new B();
C.prototype.constructor = C;

var c = new C();

// instanceof expects a constructor function

c instanceof A; // true
c instanceof B; // true
c instanceof C; // true

// isPrototypeOf, can be used on any object
A.prototype.isPrototypeOf(c); // true
B.prototype.isPrototypeOf(c); // true
C.prototype.isPrototypeOf(c); // true


一段英文说明:
The difference between both is what they are, and how you use them, e.g. the isPrototypeOf is a function available on the Object.prototype object, it lets you test if an specific object is in the prototype chain of another, since this method is defined on Object.prototype, it is be available for all objects.

instanceof is an operator and it expects two operands, an object and a Constructor function, it will test if the passed function prototype property exists on the chain of the object (via the [[HasInstance]](V) internal operation, available only in Function objects).
[color=blue]

再来看代码:
var a = [];
Array.prototype.isPrototypeOf(a) //true
a instanceof Array //true

明显却别是:instanceof是一个操作符。isPrototypeOf是一个函数。[/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值