There is a very importanthasOwnProperty()
When traversing object attributes, you can filter out the attributes from the prototype chain.
// Object
VaR man = {
Hands: 2,
Legs: 2,
Heads: 1
};
// Somewhere in the code
// A method is added to all objects.
If (typeof object. Prototype. Clone = "undefined "){
Object. Prototype. Clone = function (){};
}
// 1.
// For-in Loop
For (var I in Man ){
If (man. hasownproperty (I) {// Filter
Console. Log (I, ":", man [I]);
}
}
/* Console display results
Hands: 2
Legs: 2
Heads: 1
*/
// 2.
// Negative example:
// For-in loop without checking hasownproperty ()
For (var I in Man ){
Console. Log (I, ":", man [I]);
}
/*
Console display result
Hands: 2
Legs: 2
Heads: 1
Clone: function ()
*/
Another usehasOwnProperty()
The format is to cancel the method on object. prototype. For example:
For (var I in Man ){
If (object. Prototype. hasownproperty. Call (man, I) {// Filter
Console. Log (I, ":", man [I]);
}
}
The advantage is that when the man object re-Defines hasownproperty, it can avoid name conflicts. It also avoids all methods for searching the object with long properties. You can use the local variable "cache" it.
VaR I, hasown = object. Prototype. hasownproperty;
For (I in Man ){
If (hasown. Call (man, I) {// Filter
Console. Log (I, ":", man [I]);
}
}
Strictly speaking, do not usehasOwnProperty()
It is not an error. Based on the task and your confidence in the code, you can skip it to improve the speed of the loop. But when you are not sure about the content of the current object (and its prototype chain), addhasOwnProperty()
More secure.