0

this is my sample code...

one();


function one()
{
    function abc()
    {
      //code 
    }


    function bcd()
    {
      //code 
    }

    abc();
    bcd();
}

this is regarding php,javascript.i want to structure this code easy readable manner with or without using object oriented programming techniques.

how to call function abc from outside function one..?

Susantha7
  • 898
  • 1
  • 20
  • 38
  • 1
    Usually, you wouldn't define a function in a scope narrower than the scope you want to use it in. – Quentin Nov 24 '14 at 10:55
  • 1
    use classes or namespaces for do this. – ZiTAL Nov 24 '14 at 11:07
  • on javascript I recommend not nest many anonymous functions. if you go to nest functions is better to give some name because it is easier to see the stack and debug – rkmax Nov 24 '14 at 13:47
  • @rkmax — There aren't any anonymous functions involved. – Quentin Nov 24 '14 at 14:10
  • 1
    The following answer may be helpful to you: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Nov 24 '14 at 14:54

2 Answers2

1

The nested functions in your example is scoped within the function and are thrown away after the function one() completes; so they are not exposed.

One could use closure to expose the function ... How do JavaScript closures work? ... http://www.sitepoint.com/javascript-closures-demystified/ ... but the easiest way given your simple example is to use the abc namespace created by the function.

function abc() {
   abc.def = function () {alert("hello")}
}
abc(); // add def function to abc namespace.
abc.def(); // call def function which is part of the abc object.

To avoid object notation, one could pass a variable to the function.

function abc(operator) {
   function def() {alert("hello")}

   if (operator == def) {def()}
}
abc("def");

However this becomes more difficult to read than using object notation, because i need to look at the function to determine what is happening where abc.def() tells me I'm calling def() which is part of abc. And it causes a performance hit because def needs to be recreated on each call.

Community
  • 1
  • 1
Wayne
  • 4,760
  • 1
  • 24
  • 24
1

There are multiple ways:

// when using one() as a constructor for an object
function one()
{
    this.abc = function() { };
    this.def = function() { };
}
obj = new one();
obj.abc();


// prototype
function one()
{

}
one.prototype.abc = function() { };
one.prototype.def = function() { };
obj = new one();
obj.abc();


// module pattern
function one()
{
    var abc = function () { };
    var def = function () { };
    return {
        abc: abc,
        def: def
    }
}
obj = one();
obj.abc();


// or just assign it as a property to your function
function one()
{

}
one.abc = function() { }
one.def = function() { }
one.abc();

pick whatever suits you.

DoXicK
  • 4,784
  • 24
  • 22