问题
The default value for weakReference in the call to addEventListener() is false. Many memory issues can be resolved by using weakReferences; in fact, some industry experts "strongly recommend always using weak references with listeners".
If this is the case, can someone provide me with a good reason why weakReference defaults to true? (Note that I'm not asking why someone would ever want a listener that is not a weakReference, but rather why weakReference=false is the default)
Thanks! :)
回答1:
Another reason may be that the listener mechanism date way back from when there was no garbage collection and thus no weak references. In those days it was common place that the listeners where used with anonymous functions, so the only reference to such function would be in the listener. As the language evolved and the weak reference feature was added, it was expected that the default behavior would be the same as the one used so far, and that is no weak references.
So, in short, when the weak reference was added, it was still expected that the default behavior of the listeners was the same used so far. So the weak reference was the alternative, rather that the default.
With today’s weak references, using such anonymous functions in a listener would end up with the function being deleted almost as soon as it is added, serving no purpose at all (and probably breaking a lot of code, old and new, which depends on the strong references of the listeners.
回答2:
Using weak referencing on event listeners that modify state outside the object results in unpredictable behaviour. If you leave it to the GC to remove those listeners, you have no idea when it's actually going to do so.
You should make sure to remove the event listeners yourself when you're done with the object - as such, you want to develop without weak listeners so that it's obvious when you're forgetting to do that, instead of it being covered up by the garbage collector.
来源:https://stackoverflow.com/questions/1891869/why-does-as3-not-use-weak-references-by-default-in-event-listeners