0

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

Mou
  • 13,749
  • 38
  • 131
  • 248
  • *this* is not the same as "this" when the code runs, that's why the initial "this" is backed up in "self" ;) – Rob May 29 '15 at 11:04
  • 1
    already answered, http://stackoverflow.com/questions/17163248/whats-the-advantage-of-using-var-self-this-in-knockout-js-view-models – shammelburg May 29 '15 at 11:06
  • *self* isn't a [*keyword*](http://ecma-international.org/ecma-262/5.1/#sec-7.6.1.1). If it was, it couldn't be used as an identifier. – RobG May 29 '15 at 11:11
  • https://groups.google.com/forum/#!topic/knockoutjs/tyBOndQfmxg – Mou May 29 '15 at 11:15

1 Answers1

1

Reading the documentation it seems that ko.computed essentially returns a bound function using the second arg as the context.

So, no, it does not seem to make any practical difference in this case.

There is a subtle difference inside the bound function:

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

The self inside the function (self.first()) is creating a closure to the outer scope (where self is declared). So, the second argument defining context is then not really needed:

self.full = ko.computed(function() {
     return self.first() + " " + self.last();
  });

However, this could be changed to this without changing behaviour:

self.full = ko.computed(function() {
     return this.first() + " " + this.last();
  }, self);
Davin Tryon
  • 62,665
  • 13
  • 135
  • 126
  • u give two example code but i just do not understand what u try to say? both code look ok but not sure does 2 routine work in same way? – Mou May 29 '15 at 11:15
  • @Mou Your question is really around how binding context works in JavaScript (in general). – Davin Tryon May 29 '15 at 11:18
  • i like to know what u r trying to say by giving 3 sample code? – Mou May 29 '15 at 11:19
  • i just really do not understand what u try to say giving 3 sample code. can explain it more easy way like what u r trying to say. – Mou May 29 '15 at 11:56
  • 1
    Best to read this: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind – Davin Tryon May 29 '15 at 12:57
  • 1
    and this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures – Davin Tryon May 29 '15 at 12:57