0

Is it possible to access method/function m1 from instance of MyObjGraph? Thanks in advance for your answers

class MyObjGraph 
{
    constructor(id) 
    {
        this.drawGraph(id);
    }
    drawGraph(id)
    {
        var inId = id;
        function m1()
        {
            alert(inId);
        }
    }
}
vsync
  • 118,978
  • 58
  • 307
  • 400
  • 2
    No. In this example m1 is available only to the scope inside drawGraph. If you need a function available anywhere in the class, define it in the class same as drawGraph. – Gavin Sep 15 '19 at 16:32
  • 1
    Why don't you try it and see? (Spoiler: the answer is "no".) – Robin Zigmond Sep 15 '19 at 16:32
  • 1
    no it is a standalone function (not a method of ```MyObjGraph``` class) and it is known i the scope of ```MyObjGraph.drawGraph()``` – med morad Sep 15 '19 at 16:35
  • Possible duplicate of [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Jared Smith Sep 15 '19 at 18:18

2 Answers2

0

Nope, because it is considered as local function so the scope wouldn't be outside the drawGraph method. Only drawGraph method can access it.

sagar
  • 732
  • 1
  • 6
  • 25
0

If you can slightly modify the code, you could expose the inner method to the "outside":

class MyObjGraph {
    constructor(id) {
        this.drawGraph(id);
    }
    drawGraph(id){
        var inId = id;
        function m1(){
            alert(inId);
        }
        
        return {  //  <-------- return an object of everything you want to be exposed
          m1
        }
    }
}

const instance = new MyObjGraph();

instance.drawGraph("123").m1()

Explanation:

In your original code, the method drawGraph does not return anything, therefor it only executes code, and nothing inside of it is accessible.

For anything to be accessible directly from a function, the function needs to have a return statement, so when you invoke that function you get something in "return"... and that something, in this case below, is an Object with a single property: m1 (reference to the m1 inner function)

vsync
  • 118,978
  • 58
  • 307
  • 400