最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to call nested function from outside function - Stack Overflow

programmeradmin7浏览0评论

I have multiple instances of "batman" and need to call a nested function within "batman", from! another function that is outside of "batman".

Something like this:

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

I have multiple instances of "batman" and need to call a nested function within "batman", from! another function that is outside of "batman".

Something like this:

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

I get the error: a .hello is not a function.

what am i doing wrong? thanks in advance! :)

Share Improve this question edited Dec 13, 2017 at 10:25 Cristian Lupascu 40.6k17 gold badges105 silver badges137 bronze badges asked Dec 13, 2017 at 10:23 Frank UnderwoodFrank Underwood 7591 gold badge8 silver badges16 bronze badges 3
  • You can't. hello does not exist outside of outer function. You may want to add it on batman's prototype, then it will be accessible from it's instances. – Tushar Commented Dec 13, 2017 at 10:25
  • You cant access right away. You need to export either via prototype or this. – Ashvin777 Commented Dec 13, 2017 at 10:26
  • Possible duplicate of Javascript call nested function – James Whiteley Commented Dec 13, 2017 at 10:27
Add a ment  | 

2 Answers 2

Reset to default 6

hello is entirely private to the context of each call to batman. You can't call it from anywhere else unless you make it available somehow, for instance by assigning it to a property on the object you're creating by calling batman via new:

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

Example:

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

I suggest working through some basic JavaScript tutorials and/or books in order to get a good understanding of how things work.

There is nice js patterns out there that you can find out how to write a good js code, you can midify your code like this:

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: In this pattern and based on your code new is unnecessary.

发布评论

评论列表(0)

  1. 暂无评论