Why does `obj.foo = function() { };` not assign the name `foo` to the function?

前端 未结 3 851
旧巷少年郎
旧巷少年郎 2020-12-03 00:34

As of ES2015 (ES6), functions have proper names (including an official name property), and names are assigned when the function is created in a variety of ways

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 01:00

    Allen Wirfs-Brock has replied on the es-discuss list with the objections that prevented the TC39 consensus on the obj.foo = function() { } form:

    ...for

    cache[getUserSecret(user)] = function() {};
    

    it would leak the secret user info as the value of name

    and for

    obj[someSymbol] = function() {}
    

    it would leak the Symbol value as the value of name

    and for

     table[n]=function() {}
    

    name would likely be a numeric string

    There are counters to those objections (particularly the last one, which is extremely weak; there are many other ways a function is automatically assigned a numeric string name), but that's not the point; the point is that those were the objections raised.

    He also added that the IsPropertyReference operation that would be required (where currently there's just an IsIdentifierRef)...

    ...is a runtime operation and the new semantics require runtime determination of the name value. This is all extra runtime work that may slow down the creation of function closures that appear within loops.

    So all in all, apparently at the time the decision was taken, those objections carried the day (and quite possibly would now as well), which is why this form doesn't automatically name functions whereas so many others do.

提交回复
热议问题