Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Actionscript 3, what is the difference between the "in" operator and the "hasOwnProperty" method?

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.

like image 863
Michael Meyer Avatar asked Jul 29 '11 20:07

Michael Meyer


2 Answers

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
like image 137
Michael Meyer Avatar answered Sep 19 '22 09:09

Michael Meyer


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.

like image 20
Tyler Egeto Avatar answered Sep 20 '22 09:09

Tyler Egeto