3 ms·
Why do you need to use .hasOwnProperty anyway? var map = { a: 1, b: 2, c: 3 } for (var key in map) { console.log(m
by jvickers 12y ago
Why do you need to use .hasOwnProperty anyway?
var map = {
a: 1,
b: 2,
c: 3
}
for (var key in map) {
console.log(map[key]);
}
outputs
1
2
3
in the console, like I expect.
- swannodette 12y agoThere are many cases where this won't work.
- ddoolin 12y agoSuch as? There are cross-browser issues with Map as well.
- swannodette 12y agoLook at the other comments. ES6 Map can be properly shimmed for the last 14 years of browsers.
- shawnz 12y agoTry running this: Object.prototype.d = 4; Now you'll get: 1 2 3 4
- deleted 12y ago[deleted]
- jvickers 12y agoIf I were to run the code Object.prototype.d = 4; I'd be asking for trouble.
- shawnz 12y agoI agree, but lots of JS developers (mistakenly) think there is nothing wrong with this: Object.prototype.myDumbShim = function () { ... }; Chances are good that your code will be running in the same scope as one of these people's code eventually.
- jonpaul 12y agoBecause of prototypical inheritance. If the object's prototype has properties, you may not want iterate those. Where as `key in map` will and `hasOwnProperty()` will only return true on those properties on the object.
- jvickers 12y agoGenerally I want to look at properties from the prototype chain too.
- nogridbag 12y agoI'm not sure why you were downvoted. Yes we all understand JavaScript is prototype based and it's certainly possible for a malicious developer to muck with the prototype of your object. In the real world when you have control over the object in question (which imho is the majority of cases) there's no need to call hasOwnProperty.
- shawnz 12y agoI agree that it was a good question which shouldn't have been downvoted. But I don't think malicious developers are the real concern in this situation. Rather, it is just a matter of defensive programming. By not using hasOwnProperty (or better yet, ES6 maps), you are creating code that could break just by including a new dependency in the project.
- jvickers 12y agoThank you for your support in this difficult time.
- jvickers 12y agoIn my programming, I have not built it in a way to prevent a malicious developer from changing object prototypes. If there is actually an attack vector that gets closed by checking hasOwnProperty I'm interested.