The "in" operator and "hasOwnProperty" methods appear to be interchangeable, but I'm wondering if one is checking for inherited properties or something and the other isn't or something like that. I'm especially interested in the case of using it with a Dictionary, but I doubt that is different from other uses.
"hasOwnProperty" is described in the official docs here and "in" is described here, but if there is a difference, I didn't find it very clear.
Trusting the preciously accepted answer actually got me into a little bit of trouble. There seems to be more going on than just prototype-related differences. What I've found is that
hasOwnProperty cannot be used to see if a key is present in a Dictionary when that key is a reference type, but the in operator can.
Here's an example to demonstrate.
code:
var test:Function = function(key:*,label:String):void
{
var d:Dictionary = new Dictionary(true);
d[key] = true;
trace(label);
trace(" hasOwnProperty: " + (d.hasOwnProperty(key)?"true":"false <== !!PROBLEM!!"));
trace(" in: " + (key in d));
trace(" []: " + d[key]);
};
test({}, "indexed by object");
test("string", "key is string");
test(0, "key is number");
test(true, "key is boolean");
results:
indexed by object
hasOwnProperty: false <== !!PROBLEM!!
in: true
[]: true
key is string
hasOwnProperty: true
in: true
[]: true
key is number
hasOwnProperty: true
in: true
[]: true
key is boolean
hasOwnProperty: true
in: true
[]: true
The change I know of is in
looks up the prototype chain while hasOwnProperty
does not, most AS3 developers don't use prototype, so its not all that relevant for everyday use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With