How to Access a Function Inside a Function

Calling a Function defined inside another function in Javascript

The scoping is correct as you've noted. However, you are not calling the inner function anywhere.

You can do either:

function outer() { 

// when you define it this way, the inner function will be accessible only from
// inside the outer function

function inner() {
alert("hi");
}
inner(); // call it
}

Or

function outer() { 
this.inner = function() {
alert("hi");
}
}

<input type="button" onclick="(new outer()).inner();" value="ACTION">​

How do I call a function inside of another function?

function function_one() {    function_two(); // considering the next alert, I figured you wanted to call function_two first    alert("The function called 'function_one' has been called.");}
function function_two() { alert("The function called 'function_two' has been called.");}
function_one();

How to access a function inside a function?

No, you can't call it directly as it is a local variable to make_adder.

You need to use adder() because return adder returned the function object adder when you called make_adder(5). To execute this function object you need ()

def make_adder(x):
def adder(y):
return x+y
return adder
...
>>> make_adder(5) #returns the function object adder
<function adder at 0x9fefa74>

Here you can call it directly because you've access to it, as it was returned by the function make_adder. The returned object is actually called a closure because even though the function make_addr has already returned, the function object adder returned by it can still access the variable x. In py3.x you can also modify the value of x using nonlocal statement.

>>> make_adder(5)(10)          
15

Py3.x example:

>>> def make_addr(x):
def adder(y):
nonlocal x
x += 1
return x+y
return adder
...
>>> f = make_addr(5)
>>> f(5) #with each call x gets incremented
11
>>> f(5)
12

#g gets it's own closure, it is not related to f anyhow. i.e each call to
# make_addr returns a new closure.
>>> g = make_addr(5)
>>> g(5)
11
>>> g(6)
13

Access a variable inside a function which is inside a function in javascript?

Thanks.
I declared the variable as global and inserted value inside the inner function and then made a function call inside the function to trigger another function which call the value.

var a=0;
var surveyObjects = Parse.Object.extend(surveyObject);
var query= new Parse.Query(surveyObjects);
query.count({
success: function(count) {a =count; total();},
error:function(error){}
});

function total(){alert (a);}

When to create a nested function inside a function and when to call it from outside?

One of the main benefits of Structure 1 is that it makes internal_func locally scoped to external_func. In other words, you are making it clear that internal_func should be accessed only by external_func. Treat it just like any other regular variable that was defined inside external_func. Similar to not having global variables scattered about, sometimes you want to "hide" an implementation inside other functions.

You can then have other similarly named internal_func's in other methods and their names won't clash:

In [39]: def external_func_x2(num):
...: def f():
...: return num * 2
...: return internal_func
...:

In [40]: def external_func_x3(num):
...: def f():
...: return num * 3
...: return internal_func

One common purpose is to make functions that generate other functions based on certain conditions:

In [44]: def make_multiplier(mult):
...: def f(num):
...: return num*mult
...: return f
...:

In [45]: x4 = make_multiplier(4)

In [46]: x4(8)
Out[46]: 32

In [47]: x3 = make_multiplier(3)

In [48]: x3(8)
Out[48]: 24

You could do the same examples above with Structure 2 (or with functools.partial) but then it will be less readable, and you'll need to expose this inner f function in the outer scope/namespace, even though it's only used by the make_multiplier method. Again, think of it like hiding methods inside a class. You'll also have to pass arguments around from one function to another, instead of having a closure like what we have with Structure 1.

If you are making this make_multiplier as part of some library/API, using Structure 1 "hides" this f function and makes it a bit clearer and more readable to clients/users of the library/API that they only need to "see" the make_multiplier method.

There is also an argument for maintainability. If you need to modify make_multiplier, it's already obvious that you need to modify f, and you can be pretty sure that modifying f will not break other parts of your code, since no one uses it other than make_multiplier.

Structure 2 is your standard good practice of "splitting your big functions into smaller more manageable and reusable functions". Its major advantages over Structure 1 are testability and reusability. It is much easier to test and mock out _internal_func2 directly, without needing to call external_func2, which is great if external_func2 is especially complicated in itself to call. It would also be very difficult to write tests that directly target a nested inner function.

It also makes _internal_func2 reusable by other methods. Comparing it to the example above for Structure 1, if you find yourself writing the same inner f nested inside many external_func's, then it's probably better to move that out and convert to Structure 2 style.

call a nested function (function inside another function)

THIS IS NOT SOMETHING YOU SHOULD DO, but you could create a nested function attribute like so:

def foo():
# for closures or strictly local function
# then this is useful!
# ugly hack other wise to try and create methods.
def bar():
print('bar')

# if there are multiple function, return a container...
return bar

Then:

foo.bar=foo()
foo.bar()
# prints 'bar'

BUT, this is far easier with a class:

class Foo:
# class can hold related methods, setters and getters,
# protected variables, etc.
# Python is DESIGNED to do this.
def bar(self):
print('bar')

Then:

f=Foo()
f.bar()
# prints 'bar'

Why is it easier?

  1. Because Python is designed to use the second example, a class, but the first example is a hack. The ways to use classes are well documented and tested.
  2. It does not scale well. Each function attribute needs to be added from the OUTSIDE of the function.
  3. You will run into local vs global namespace issues if you try and change variables. Classes gracefully support both instance and class data.

It is horrible -- don't do it. Use a class or a module to hold methods.


After a morning coffee, you can potentially do something like this if you really want to add function attributes -- Use a decorator to monkey patch a function:

def add_func_to(function):
# decorator to add function attributes
def attr_f(new_func):
setattr(function, new_func.__name__, new_func)
return new_func
return attr_f

# some function to add an attribute function to:
def foo():
pass

@add_func_to(foo)
# added attribute function below
def attr_f(string):
print(string)

Test it:

>>> foo.attr_f('test')
test

This is still limited vs a class or module since you will be limited to using global or passed variables. It is more applicable if you just want to add a function attribute to an existing function and be done with it...

How to call function inside function through only HTML

It isn't possible to call setLayout at all.

Functions defined in other functions are scoped to that function. They can only be called by other code from within that scope.

If you want to to be able to call customize.setLayout then you must first create customize (which can be a function, but doesn't need to be) then you need to make setLayout a property of that object.

customize.setLayout = function setLayout(text) { /* yada yada */ };

Call function inside a function in a class from another function in another class in Python

class A():
def f1(self):
def f2(self, x):
return 'f2' + str(x)
return 'f1', f2(self, 'XoXo')

class B(A):
def f3(self):
self.x = self.f1()
self.y = self.x[0]
self.z = self.x[1]
return 'f3' + self.y + self.z

b = B()
print(b.f3())


Related Topics



Leave a reply



Submit