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?).

2
  • 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. Commented Aug 27, 2014 at 16:35
  • @Barmar: Yeah, I saw. I wanted to edit the title and then reopen it myself :-) Commented Aug 28, 2014 at 8:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

That explains why they need to do target['subscribe'], but why do they ALSO need to do target.subscribe?
@Barmar That's the one that will be minified, thus saving space.
Wouldn't it save more space if there were no second assignment at all?
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.
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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.