-2

I have a functions A B with same method in them. I want to access this method from another function. Depends upon some condition ill choose any one of version!

    function A() {
        var method = function() {
            // do something..        
        }        
    }

    function B() {
        var method = function() {
            // do something..        
        }        
    }

    function other() {
        // access method from function A() or B();
    }

is there any way to access using objects like we do in JAVA or any other way?

bharat
  • 330
  • 1
  • 3
  • 13
  • Either, `A` needs to `return` the `method` and you invoke `A` to get it. Or, `A` is a constructor and you set `this.method = method` inside `A`, then do `foo = new A; foo.method`. Or, create `method` outside of `A` as i.e. `A.method = function () {}`, and you can access as `A.method` – Paul S. Aug 09 '14 at 13:14

1 Answers1

0

You could technically make "method" global by putting it on the window global object:

function A() {
    window.method = function() {
        // do something..        
    }        
}

function other() {
    // access window.method 
}

Generally, this isn't what you want to do. If you find yourself having to do weird hacks like this to get access to a method it usually means something wrong. You should try to pull the method out into a shared scope where it's accessible where it's needed.

joeltine
  • 1,610
  • 17
  • 23