8

I am working through Knockoutjs tutorial. And one thing seems weird to me. I am currently in part 2:

http://learn.knockoutjs.com/#/?tutorial=collections

And in this part in every "class", "this" is being assigned to "self".. it was not the case in the first one?

Why would someone do this? Is it just whoever wrote that particular code has python addiction, or is there some actual benefits to this?

galdikas
  • 1,424
  • 4
  • 17
  • 37
  • 4
    possible duplicate of [JS: var self = this?](http://stackoverflow.com/questions/337878/js-var-self-this) And for further reading: And for further reading:http://stackoverflow.com/questions/9589419/difference-between-knockout-view-models-declared-as-object-literals-vs-functions – nemesv Apr 11 '13 at 19:14

1 Answers1

7

Since "this" refers to different objects depending on context, one can save a reference to a particular object by assigning it to another variable, for example "self".

Whistletoe
  • 563
  • 2
  • 10
  • 1
    I'd also add it isn't a knockout specific question really, it is a general javascript development pattern quite often used (including in node). – lucuma Apr 11 '13 at 19:14
  • While this is true, it appears knockout's use is frivolous in that example. There is not context switching and you can safely change "self" into "this" and the example works fine. Perhaps they do this because later in the tutorial there is context switching? – MikeMurko Apr 11 '13 at 19:15
  • Yes, i would think it sometimes becomes a habit. – Whistletoe Apr 11 '13 at 19:16
  • 1
    In the computeds in the tutorial, `self` needs to be used or the context is not correct. ko.computeds do take a second argument that specifies the context as well, so it could be written using either pattern. These computeds come in later in the lesson. – RP Niemeyer Apr 11 '13 at 19:21
  • @MikeMurko I'm not sure they are consistent with their tutorials as I just saw one that doesn't use the self assignment. http://learn.knockoutjs.com/#/?tutorial=custombindings Hopefully the OP has his answer especially by the second example in nemesv's comment. – lucuma Apr 11 '13 at 19:21
  • I think its better to let "this" have the correct contex instead of using. Both computed and subscribe take a second parameter that is the context, i make it a habit to set it to this. You can also use this.myMethod.bind(this) – Anders Apr 11 '13 at 20:50