问题
I am trying to access a variable which exists in another function, but I am not able to, it gives me undefined for the function through which (getMess() as below) I am doing that. As per the code below, I want the "value1" accessed through myfunction1, as shown below. Code:
var namespace ={
myfunction1: function(){
namespace.myfunction2.getMess(); // I need to access value1 here in this function
},
myfunction2: function(message1,message2){
var value1 = message1;
var value2 = message2;
return{
getMess: function(){ return value1;}
getLab: function() { return value2;}
}
}
}
namespace.myfunction2("hello","bye"); // this basically just sets the 2 values on page load
I just posted another question with the original problem : Read resource file entry in javascript - MVC application
回答1:
You could do:
myfunction2: function(message1,message2){
var value1 = message1;
var value2 = message2;
namespace.myfunction2.getMess: function(){ return value1;}
namespace.myfunction2.getLab: function() { return value2;}
}
but that's pretty awful (assigning properties to a function object). Better to refactor the whole thing using the module pattern to emulate private and privileged members.
e.g.
var namespace = (function() {
// Private members
var value1, value2;
return {
// Privileged methd to read private member values
fn1: function() {
return namespace.fn2.getMess1();
},
// Privileged methods to set and get private member values
fn2: {
setMess: function(message1, message2) {
value1 = message1;
value2 = message2;
},
getMess1: function() {
return value1;
},
getMess2: function() {
return value2;
}
}
}
}());
namespace.fn2.setMess("hello","bye");
alert(namespace.fn1()); // hello
回答2:
This seems very strange to me, but first off you were retuning an object and missing a ,
inbetween the 2 functions you were trying to return.
var namespace ={
myfunction1: function(){
var jamie = namespace.myfunction2("hello","bye"); // save returned value so we can use them later.
console.info(jamie.getMess); //as we already executed the value just refer to them
},
myfunction2: function(message1,message2){
var value1 = message1;
var value2 = message2;
return{
getMess: function(){ return value1;}(), //return self executing functions to return values without the need to run them again.
getLab: function(){ return value2;}()
}
}
}
namespace.myfunction1();
While I'm still not sure what you're trying to achieve this is how I would pass values between 2 functions whilst not declaring variables to namespace
and just assigning values globally that way.
来源:https://stackoverflow.com/questions/19446634/accessing-variable-in-another-function-returns-undefined-javascript