【问题标题】:How to call nested function from outside function如何从外部函数调用嵌套函数
【发布时间】:2018-05-27 04:52:08
【问题描述】:

我有多个“蝙蝠侠”实例,需要在“蝙蝠侠”中调用嵌套函数,来自! “蝙蝠侠”之外的另一个功能。

类似这样的:

var a = new batman();
var b = new batman();
var c = new batman();
robin();


function batman(){
    function hello(){
        console.log("hello world!");
    }
}

function robin(){
    a.hello();
}

我收到错误:.hello 不是函数。

我做错了什么? 提前致谢! :)

【问题讨论】:

  • 你不能。 hello 在外部函数之外不存在。您可能想将它添加到batman 的原型上,然后可以从它的实例中访问它。
  • 您无法立即访问。您需要通过原型或此导出。

标签: javascript


【解决方案1】:

hello 对于每次调用batman 的上下文完全私有。除非您以某种方式使其可用,否则您不能从其他任何地方调用它,例如通过调用 batman 通过 new 将其分配给您正在创建的对象的属性:

function batman(){
    this.hello = function() {
        console.log("hello world!");
    };
}

例子:

var a = new batman();
//var b = new batman();
//var c = new batman();
robin();

function batman(){
    this.hello = function() {
        console.log("hello world!");
    };
}

function robin(){
    a.hello();
}

我建议阅读一些基本的 JavaScript 教程和/或书籍,以便更好地理解事情的工作原理。

【讨论】:

    【解决方案2】:

    那里有很好的 js 模式,您可以了解如何编写好的 js 代码,您可以像这样修改您的代码:

    var a = new batman('a');
    var b = new batman('b');
    var c = new batman('c');
    robin();
    
    function batman(str){
        function hello(){
            console.log("hello world! Called from: "+str);
        }
        return {
            hello : hello
        };
    }
    
    function robin(){
        a.hello();
    }
    

    Learning JavaScript Design Patterns
    P.S:在这种模式下,根据您的代码,new 是不必要的。

    【讨论】:

      猜你喜欢
      • 2012-11-20
      • 2017-12-02
      • 2021-05-19
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      相关资源
      最近更新 更多