Reputation: 32893
I declared two functions using function expression innerone
and innertwo
. I first declared innerone
and after that innertwo
. Inside innerone
I am calling innertwo
function. But my concern is that I am declaring innertwo
after innerone
using function expression which means innertwo
is not hoisted. So why these functions work in this order? Is it mandatory to change their order?
Here is code
var one = function () {
var innerone = function () {
innertwo();
},
innertwo = function () {
console.log('innertwo');
};
return {
innerone: innerone
};
};
var o = new one();
o.innerone();
Upvotes: 0
Views: 103
Reputation: 707706
You asked in your comment for simpler ways to write this code, so here are a couple simpler ways. The first still returns the structure and can be just called as a function without new
. The second adds a property to the function object, but still preserves the private function innertwo()
. The second option looks the cleanest to me.
Option 1:
function one() {
function innertwo() {
console.log('innertwo');
}
return {
innerone: function() {
innertwo();
}
};
}
var o = one(); // new is not needed here
o.innerone();
Option 2:
function one() {
function innertwo() {
console.log('innertwo');
}
this.innerone = function () {
innertwo();
};
};
var o = new one();
o.innerone();
Upvotes: 0
Reputation:
It's working because innerone is called only when you call it. And by the time it's called innertwo is defined.
Upvotes: 5