hasOwnProperty和isPrototypeOf
生活随笔
收集整理的這篇文章主要介紹了
hasOwnProperty和isPrototypeOf
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
hasOwnProperty和isPrototypeOf hasOwnProperty:是用來(lái)判斷一個(gè)對(duì)象是否有你給出名稱的屬性或?qū)ο?此方法無(wú)法檢查該對(duì)象的原型鏈中是否具有該屬性,該屬性必須是對(duì)象本身的一個(gè)成員。
isPrototypeOf是用來(lái)判斷要檢查其原型鏈的對(duì)象是否存在于指定對(duì)象實(shí)例中,是則返回true,否則返回false。
in 操作檢查對(duì)象中是否有名為 property 的屬性。也可以檢查對(duì)象的原型,判斷該屬性是否為原型鏈的一部分.
Java代碼 復(fù)制代碼
hasOwnProperty:
var obj = {a:1,b:2}
obj.hasOwnProperty('a') isPrototypeOf:
function F(){}
var fn = new F()
F.prototype.isPrototypeOf(fn)
前者是判斷對(duì)象中是否存在某個(gè)屬性,后者是判斷對(duì)象是否是原型鏈的對(duì)象。
那么isPrototypeO與instanceof又有什么區(qū)別?
Java代碼 復(fù)制代碼
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
一段英文說(shuō)明:
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]
再來(lái)看代碼:
Java代碼 復(fù)制代碼
var a = [];
Array.prototype.isPrototypeOf(a) //true
a instanceof Array //true
明顯卻別是:instanceof是一個(gè)操作符。isPrototypeOf是一個(gè)函數(shù)。
?
posted on 2013-04-11 14:20 Spider024 閱讀(...) 評(píng)論(...) 編輯 收藏轉(zhuǎn)載于:https://www.cnblogs.com/spider024/archive/2013/04/11/3014426.html
總結(jié)
以上是生活随笔為你收集整理的hasOwnProperty和isPrototypeOf的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 树形动规_(战略游戏)
- 下一篇: 利用AOP重构代码