I can't figure out how to access pubOuter, can anyone figure this one out? It keeps returning undefined , because I can't find a way how pass outer from inner2() function. Or I'm missing something obvious. Many thanks.
Javascript
var myObject = (function(){
var outer;
function inner1(IN_number){
outer = IN_number*2;
}
function inner2(){
inner1(10);
return outer;
}
return {
pubFnInner1: inner1,
pubFnInner2: inner2,
pubOuter: outer
};
})();
$("#click").on("click", function(){
console.log("outer" + myObject.pubOuter);
});
HTML
<button id="click">Click</button>
You are successfully accessing the putOuter
property. The problem is that it hasn't been set to anything before you're using it.
I've modified the code to initialize outer
to 1
. Otherwise, when you multiply it by IN_number
in the inner1
function, it will result in NaN
.
var myObject = (function(){
var outer = 1;
function inner1(IN_number){
outer = IN_number*2;
}
function inner2(){
inner1(10);
return outer;
}
return {
pubFnInner1: inner1,
pubFnInner2: inner2,
pubOuter: outer
};
})();
$("#click").on("click", function(){
console.log("outer" + myObject.pubOuter);
myObject.pubFnInner1(10);
console.log("outer" + myObject.pubOuter);
// or combine both steps by using your pubFnInner2 method.
console.log("outer" + myObject.pubFnInner2());
});
pubOuter
is undefined because you're assigning it to outer
which is undefined because you never run inner1
, you need to do this:
var myObject = (function(){
var outer;
function inner1(IN_number){
outer = IN_number*2;
}
function inner2(){
inner1(10);
return outer;
}
return {
pubFnInner1: inner1(),
pubFnInner2: inner2(),
pubOuter: outer
};
})();
$("#click").on("click", function(){
console.log("outer" + myObject.pubOuter);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.