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

拟墨画扇 提交于 2019-12-08 14:47:05

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/6878882/in-actionscript-3-what-is-the-difference-between-the-in-operator-and-the-has

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!