-2

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! :)

Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137
Frank Underwood
  • 681
  • 1
  • 8
  • 16
  • 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 Dec 13 '17 at 10:25
  • You cant access right away. You need to export either via prototype or this. – Ashvin777 Dec 13 '17 at 10:26
  • Possible duplicate of [Javascript call nested function](https://stackoverflow.com/questions/8817872/javascript-call-nested-function) – James Whiteley Dec 13 '17 at 10:27

2 Answers2

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

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.

Colin Cline
  • 1,291
  • 1
  • 12
  • 25