0

I've just found the following line in Knockout's source code:

target.subscribe = target['subscribe'] = function …

Why are they assigning the function to the same property twice? The only difference is the way they access it. As far as I know this shouldn't make a difference with the given property name (JavaScript property access: dot notation vs. brackets?).

Community
  • 1
  • 1
ctusch
  • 940
  • 9
  • 20
  • 1
    @Bergi I reopened this because it's not a duplicate of the general question of which should be used. This question is about why some code is using BOTH, seemingly redundantly. – Barmar Aug 27 '14 at 16:35
  • @Barmar: Yeah, I saw. I wanted to edit the title and then reopen it myself :-) – Bergi Aug 28 '14 at 08:05

1 Answers1

4

It's possible that this is done to prevent things breaking when code is minified.

target.subscribe can be minified to something like target.a, however there may be code that relies on target.subscribe still being there. For instance, you might have:

var x = 'subscribe';
target[x](something);

Assigning to both will allow the minifier to do its work, without breaking support for expression access.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • That explains why they need to do `target['subscribe']`, but why do they ALSO need to do `target.subscribe`? – Barmar Aug 27 '14 at 16:31
  • @Barmar That's the one that will be minified, thus saving space. – Niet the Dark Absol Aug 27 '14 at 16:32
  • 1
    Wouldn't it save more space if there were no second assignment at all? – Barmar Aug 27 '14 at 16:33
  • Certainly. But if you have `target.subscribe` many times in your code, then they can all be minified. `target.subscribe` is the preferred format when minifying. `target['subscribe']` is simply there to provide compatibility for expression-based access. – Niet the Dark Absol Aug 27 '14 at 16:35
  • That makes sense! I checked the minified version and it reads `b.V=b.subscribe=function...`. But that also means you end up with two different properties and you always need to be aware which one you are reading or writing. Sounds like a good source for bugs. – ctusch Aug 28 '14 at 15:38
  • @user232986 Maybe if you're working with strings or numbers, but for a function (or any other object) there is only ever one object with two references pointing to it - no bugs there. – Niet the Dark Absol Aug 28 '14 at 15:51