当前位置: 代码迷 >> Web前端 >> hasOwnProperty跟isPrototypeOf
  详细解决方案

hasOwnProperty跟isPrototypeOf

热度:112   发布时间:2012-11-10 10:48:51.0
hasOwnProperty和isPrototypeOf
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)



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


那么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]