Difference between prop in obj and obj.hasOwnProperty(prop) and obj[prop]?
Should I use one over the other? Is using them all together better? Th开发者_如何学Pythonanks.
prop in obj
checks whetherobj
has a property namedprop
at all, even if it's just inherited from a prototype.obj.hasOwnProperty(prop)
checks whetherobj
itself holds a property namedprop
; it ignores properties inherited from prototypes.obj[prop]
gets the value of theprop
property.
Use whichever one is appropriate for what you're trying to accomplish
Note: In all three cases, prop
must be a string.
Just to give an example for this:
var animal = {"legs": 4};
var dog = {"barks" : true};
dog.__proto__ = animal; // JS inheritance (dog inherits from animal)
now this means that:
console.log("legs" in dog); // TRUE - due to JS inheritance and since 'in' key looks into inherited prototypes
console.log(dog.hasOwnProperty("legs")); // FALSE
console.log(dog.hasOwnProperty("barks")); //TRUE
prints
true
false
true
Note one more thing: If dog had "legs" property of lets say 5 (hhmm spooky i know), so the 'in' operator ("legs" in dog) will refer to the "legs" property which is declared in the dog object and not the inherited "legs" which comes from animal object. e.g.:
var animal = {"legs": 4};
var dog1 = {"barks": true};
var dog2 = {"barks": true, "legs": 5};
dog1.__proto__ = animal;
dog2.__proto__ = animal;
console.log(dog1.legs);
console.log(dog2.legs);
console.log("legs" in dog2) // 'in' refer to the un-inherited "legs" of dog2
prints
4
5
true
精彩评论