Javascript – Calling method inside another method in javascript


I am having a JavaScript namespace say


  CA: function() {
  B: function() {
    var test='test';
    var result='t1';

    C: function() {
      return 'test1';    

   return result; 

Now when I am executing such code it is giving that TypeError: this.C is not a function. Can somebody tell me why it is so. I know it is something related with lexical scoping but am unable to understand this.

Best Solution

You have to be careful when you use this to identify anything in Javascript because each time you change scope "this" changes.

Assigning the 'this' reference to it's own variable helps get around this.

var a = new function() {
    var self = this;

    self.method = function() { alert('hiya'); };

    var b = function() {
        this.method(); // this isn't 'a' anymore?
        self.method(); // but 'self' is still referring to 'a'