开发者

Difference between prop in obj and obj.hasOwnProperty(prop) and obj[prop]?

开发者 https://www.devze.com 2023-04-09 10:22 出处:网络
Should I use one over the other? Is using them all together better? Th开发者_如何学Pythonanks. prop in obj checks whether obj has a property named prop at all, even if it\'s just inherited from a prot

Should I use one over the other? Is using them all together better? Th开发者_如何学Pythonanks.


  • prop in obj checks whether obj has a property named prop at all, even if it's just inherited from a prototype.

  • obj.hasOwnProperty(prop) checks whether obj itself holds a property named prop; it ignores properties inherited from prototypes.

  • obj[prop] gets the value of the prop 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号