Calling method inside another method in javascript?

前端 未结 4 1527
北荒
北荒 2021-02-07 21:05

I am having a JavaScript namespace say

A={

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

    C: functi         


        
4条回答
  •  一生所求
    2021-02-07 22:00

    I am actually surprised that your code doesn't give you error on the 'C:' line.

    Anyway, your syntax to define a function is not correct. Define it using the var keyword. Also, notice that I created the 'closure' so that the function C can access 'this'. See the code below:

    A={
    
      CA: function()
      {
        this.B();
      },
    
      B: function()
      {
        var test='test';
        var result='t1';
    
        var self = this;
        var C = function()
                {
                  self.test='test1';
                  .....
                  .....
                  return 'test1';    
                }
    
       result=C();
       return result; 
      }
    }
    

    If you want to assign C to 'this' object, you can also do:

    A={
    
      CA: function()
      {
        this.B();
      },
    
      B: function()
      {
        var test='test';
        var result='t1';
    
        var self = this;
        this.C = function()
                 {
                  self.test='test1';
                  .....
                  .....
                  return 'test1';    
                 };
    
       result= this.C();
       return result; 
      }
    }
    

提交回复
热议问题