In this conclusion to a three-part series on nesting JavaScript functions, we see how nested functions can be used as object types. We shall make it simple. We shall consider only the case where there is only one level of nested functions.
Nested JavaScript Functions as Objects - Nested Function as Method (Page 3 of 5 )
Here we want to see if a nested function can be used as a method in an object type. As I said earlier, in this series, we only consider the first level of nested functions. The example here is the modified version of the example code above. The second function above is now a nested function in the constructor function. This is the code:
<html>
<head>
<script type="text/JavaScript">
function functionType1()
{
alert('This is function type one');
}
function ObjectType()
{
this.propertyType1 = "Yes type one";
this.methodType1 = functionType1;
function functionType2()
{
alert('This is function type two');
}
this.methodType2 = functionType2;
}
var theObject = new ObjectType();
</script>
</head>
<body>
<button type="button" onclick="theObject.methodType1()">Call Object Type Method</button>
The functionType1() function is outside the constructor function. This function will become the first method of the constructor function. Next you have the constructor function. The first statement in this object type gives a property for the object type. The second statement gives the method, using the function outside the constructor function.
This is the interesting part: you have the nested function next, named functionType2. After that, you have a method declared using this function, which is inside the constructor function. The name of the method is methodType2.
Outside the constructor function, the object is created; no method is created for the object outside the constructor function. That covers the script.
You now have two HTML buttons. The first button executes themethod whose function is not nested. The second button executes the method whose function is nested. All the method calls are successful.
We conclude that you can have a nested function as a method in a constructor function.
Question of Privacy
You cannot call a nested function from outside the outermost function. However, if that function were a first level nested function in a constructor function, and if it were assigned as a method, then it could be called as you would call any method of an object created from the constructor function.