Is there any difference between this and self keyword usage in knockout js

339 views
Skip to first unread message

Tridip Bhattacharjee

unread,
May 29, 2015, 7:59:03 AM5/29/15
to knock...@googlegroups.com

i just wonder is there any difference between self and this keyword usage or both same

see this example which use this keyword

var ViewModel = function(first, last) { this.first = ko.observable(first); this.last = ko.observable(last); this.full = ko.computed(function() { return this.first() + " " + this.last(); }, this); };



see this example which use self keyword instead of this keyword


var ViewModel = function(first, last) { var self=this; self.first = ko.observable(first); self.last = ko.observable(last); self.full = ko.computed(function() { return self.first() + " " + self.last(); }, self); };

which approach is good and why accepted ? thanks

Brian George

unread,
May 29, 2015, 8:28:16 AM5/29/15
to knock...@googlegroups.com
It is my understanding that "this" works just as well as "self".  However, the biggest difference is the confusion.  If you use "this" for everything, you will end up with a lot of confusion as to what "this" actually is when you are in sub-functions, and inline functions.  The "self" variable removes that confusion and is always pointing at the view model class.  I ALWAYS use a "self" variable while in knockout to avoid any confusion later on.

--
You received this message because you are subscribed to the Google Groups "KnockoutJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to knockoutjs+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Michael Best

unread,
May 29, 2015, 4:56:02 PM5/29/15
to knock...@googlegroups.com
If you're using self, there's no need to pass it to the computed. So you should do it like this:

self.full = ko.computed(function() { return self.first() + " " + self.last(); });
Reply all
Reply to author
Forward
0 new messages