Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling method inside another method in javascript?

I am having a JavaScript namespace say

A={

  CA: function() {
    this.B();
  },
  B: function() {
    var test='test';
    var result='t1';

    C: function() {
      this.test='test1';
      .....
      .....
      return 'test1';    
    }

   result=this.C();  
   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.

like image 557
Ashish Jain Avatar asked Jul 07 '09 14:07

Ashish Jain


People also ask

Can we call a method inside a method in JavaScript?

method2 = function(){ me. method1("method1 called from method2"); } } var f as new myfunction(); f. method2(); This example shows how one can call a method from within another method or from outside using an instance of the function.

Can you call a method inside the same method?

But yes, what you're trying to do is possible. It's called recursion, or recursive programming. It's when a function calls itself or multiple functions call each other repeatedly. It's useful for some stuff.

How do you call a function from another function in JavaScript?

To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.

How do you call a method inside a class in JavaScript?

var test = new MyObject(); and then do this: test. myMethod();


2 Answers

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'
    };

};
like image 156
hugoware Avatar answered Sep 20 '22 09:09

hugoware


I think the problem is that when this.C() is executed inside the function referred to by B, this refers to the object that contains B, that is, object A. (This assumes B() is called within the context of A)

The problem is, C does not exist on the object A, since it's defined within B. If you want to call a local function C() within B, just use C().

EDIT: Also, I'm not sure what you've posted is valid JavaScript. Specifically, B should be defined this way, since you can't use the object:property syntax within a function.

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

  var C = function()
  {
    this.test='test1';
    return 'test1';    
  }

 result=C();  
 return result; 
}
like image 26
Peter Avatar answered Sep 19 '22 09:09

Peter