在javascript中调用另一个方法内的方法? [英] Calling method inside another method in javascript?

查看:142
本文介绍了在javascript中调用另一个方法内的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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; 
  }
}

现在,当我执行这样的代码时,它正在给出TypeError:this.C不是函数。有人可以告诉我为什么会这样。我知道它与词汇作用域有关,但我无法理解这一点。

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.

推荐答案

我认为问题是当 this.C() B 引用的函数内执行,指的是包含 B 的对象,即object A 。 (假设 B() A 的上下文中调用

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)

问题是, C 在对象 A 上不存在,因为它是在<$中定义的C $ C> B 。如果要在 B 中调用本地函数 C(),只需使用 C( )

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().

编辑:
另外,我不确定你发布的是有效的JavaScript。具体来说, B 应该以这种方式定义,因为你不能在函数中使用object:property语法。

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

这篇关于在javascript中调用另一个方法内的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆