求问一个基础的JS问题我试着用对象的方式封装我的函数,但遇到些不明白的地方。
有个对象getMm,包含索引值, 填充数组内容,和一个函数,通过数组索引返回数组的值。
先上测试代码:function getMm(tt)
{
var Temp;
this.index1 = 10;
this.index2 = 11;

var init = function(vtt)
{
alert("POP1:  " + this.index1);
Temp = new Array();
Temp[this.index1] = vtt+"012345";
Temp[this.index2] = vtt+"20123456";
}
init(tt); this.getValue = function (id)
{
return (Temp[id]);
}
}function onTESTTEST()
{
var Test = new getMm("test");
alert("POP2:   " + Test.index1);
alert("POP3:   " + Test.getValue(Test.index1));
}1、生成getMm对象Test
2、通过索引Test.index1和Test对象的函数Test.getValue获得数组对应的值。运行打印的提示信息:
POP1:  undefined
POP2:  10
POP3:  undefined
问题在于类似构造函数的init中,为什么不能访问this.Index1 ?
假如,我把this.index1 = 10; 修改成 var index1 = 10, 那么Init函数中可以访问,但类的外部就无法通过对象直接访问index1了。function getMm(tt)
{
var Temp;
var index1 = 10;
var index2 = 11;

var init = function(vtt)
{
alert("POP1:  " + index1);
Temp = new Array();
Temp[index1] = vtt+"012345";
Temp[index2] = vtt+"20123456";
}
init(tt); this.getValue = function (id)
{
return (Temp[id]);
}
}function onTESTTEST()
{
var Test = new getMm("test");
alert("POP2:   " + Test.index1);
alert("POP3:   " + Test.getValue(Test.index1));
}运行弹出的内容:
POP1:   10
POP2:   undefined
POP3:   undefined我想实现:
通过类封装数据数组,通过类定义的索引值获得对应的值。我的疑惑:
JS中的几种定义让我混淆了。
类里面的函数定义:function TEST()
{
   a = 0;
   var b=0;
   this.c = 0;   var init_a = function()
   {
   }
   
   this.init_b = function()
   {
   }
};
a\b\c 定义有什么不同?
init_a\init_b 定义有什么不同?函数内部分别对a\b\c三者的作用域又如何? ==== 求解惑
javascript对象

解决方案 »

  1.   

    a是全局变量,相当于window.a, b是局部变量,作用域在这个function内,c是实例属性;
    init_a是TEST的内部方法,而init_b是TEST的实例方法。
    你第一段代码的第九行之所以undefined,因为这里的this已经不是属于getMe了,而是属于init了,所以是undefined了。
      

  2.   

    第一个代码,init并不是对象实例方法,有点像面向对象语言的私有静态方法,静态方法中当然不能用this。由于init初始化不成功,所以POP3获取Tmp[10]也为undefined其他的也差不多,楼主去了解什么是对象成员和内部方法
      

  3.   

    根据楼上两位的分析,修改测试代码如下:function getMm(tt)
    {
    var Temp;
    this.index1 = 10;
    this.index2 = 11;

    var init = function(curobj, vtt)
    {
    alert("POP1:  " + curobj.index1);
    Temp = new Array();
    Temp[curobj.index1] = vtt+"012345";
    Temp[curobj.index2] = vtt+"20123456";
    };
    init(this, tt); this.getValue = function (id)
    {
    return (Temp[id]);
    };
    };function onTESTTEST()
    {
    var Test = new getMm("test");
    alert("POP2:   " + Test.index1);
    alert("POP3:   " + Test.getValue(Test.index1));
    }输出结果正确:
    POP1:   10
    POP2:   10
    POP3:   test012345初始化函数增加参数,讲当前getMm对象传递进去:
    var init = function(curobj, vtt)这样实现初始化属性成员,同时属性又能被外部直接使用(this.xxx 方式定义的成员),不知道有没有什么不妥?
      

  4.   

    多谢 1、2#的回帖, ThankYou