In Actionscript 3, what is the difference between

2019-06-15 00:23发布

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.

2条回答
▲ chillily
2楼-- · 2019-06-15 00:52

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
查看更多
相关推荐>>
3楼-- · 2019-06-15 00:54

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.

查看更多
登录 后发表回答