Wednesday, 12 July 2017

Avoiding uncertainty with "this"

Most of the time, we don't know what is "this"? Is it a "window", jQuery object, or what is it. It is difficult to debug and make the code to work.

One of the easiest solution that I found is to capture the context into "self" and then all public functions to be declared with the object function. For example, sayHelo() will always referring to the same context as you call the setMyName().

function myClass() {
  var self = this;
  var name;

  this.setMyName = function (s) { name = s; };
  this.getMyName = function() { return name; };
 
  this.sayHelo = function() { return self.getMyName(); };

}

var c = new myClass();
c.setMyName('Mickey');
console.log(c.sayHelo());


We are moving

We are moving this blog to our new blog site: https://ciysys.com/blog/nodejs.htm