问题描述
我试图访问一个变量存在于另一个函数,但我不能,它给我未定义的函数通过(getMess()如下)我在做。
根据下面的代码,我想通过myfunction1访问value1,如下所示。
代码:
var namespace = {
myfunction1:function(){
namespace。 myfunction2.getMess(); //我需要访问value1这里在这个函数
},
myfunction2:function(message1,message2){
var value1 = message1;
var value2 = message2;
return {
getMess:function(){return value1;}
getLab:function(){return value2;}
}
}
}
namespace.myfunction2(hello,bye); //这基本上只是设置页面加载的两个值
我刚刚发布了另一个问题与原始问题:
myfunction2:function(message1,message2){
var value1 = message1;
var value2 = messages2;
namespace.myfunction2.getMess:function(){return value1;}
namespace.myfunction2.getLab:function(){return value2;}
}
但是这是非常可怕的(为一个函数对象分配属性)。最好使用模块模式重构整个事件,以。
例如
var namespace =(function(){
//私有成员
var value1,value2;
return {
//特权模式读取私有成员值
fn1:function ){
return namespace.fn2.getMess1();
},
//设置和获取私有成员值的特权方法
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
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
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
这篇关于访问另一个函数中的变量,返回undefined - JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!