hasOwnProperty:是用來判斷一個對象是否有你給出名稱的屬性或對象。不過需要注意的是显沈,此方法無法檢查該對象的原型鏈中是否具有該屬性软瞎,該屬性必須是對象本身的一個成員。
isPrototypeOf:是用來判斷要檢查其原型鏈的對象是否存在于指定對象實例中,是則返回true铜涉,否則返回false智玻。
instanceof() vs isPrototypeOf() hasOwnProperty() vs propertyIsEnumerable()
這幾個方法在js的高級編程中經常用到,對于新手來說可能還不知道他們有什么區(qū)別芙代,我把我的體會總結下來吊奢,供大家參考:
首先,定義一個對象:
function Parent() {this.name = "wenbo";}
Parent.prototype.alertP = function() {
alert("Parent");
}
function Child() {this.age = 23;}
Child.prototype.alertC = function() {
alert("Child");
}
function F() {}
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
var child = new Child();
1,instanceof() vs isPrototypeOf():
instanceof:判斷該對象是否為另一個對象的實例纹烹。
console.log(child instanceof Parent); //true
console.log(child instanceof Child); //true
isPrototypeOf:判斷一個對象象是否為一個實例的原型页滚。
Parent.prototype.isPrototypeOf(child);//true
Child.prototype.isPrototypeOf(child);//true
hasOwnProperty() vs propertyIsEnumerable():
hasOwnProperty:判斷對象是否有某個特定的屬性,(注意說的是對象的屬性铺呵,而不是對象原型的屬性)必須用字符串指定該屬性裹驰。
Parent.hasOwnProperty("name");//true
Child.hasOwnProperty("age");//true
Parent.hasOwnProperty("alertP");//false
Child.hasOwnProperty("alertC");//false
propertyIsEnumerable:判斷給定的屬性是否可以用 for...in 語句進行枚舉。由于 for ... in 枚舉是包含原型鏈上的屬性的片挂,但propertyIsEnumerable作用于原型方法上時幻林,始終是返回false的,你可以這么認為音念,for...in可以枚舉對象本身的屬性和原型上的屬性沪饺,而propertyIsEnumerable只能判斷本身的屬性是否可以枚舉。此外闷愤,預定義的屬性不是可列舉的整葡,而用戶定義的屬性總是可列舉的。所以如果你只想遍歷對象本身的屬性讥脐,可以:
for (var key in obj) {
if (obj.hasOwnProperty(key) {
//do something
}
}