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