梦的尽头...
程序人生

<script>
//对象的定义方法一(直接定义一个对象)
var source =
{
a:70,
b:'123',
x:function()
{alert(this.a);}
};
//由于是直接定义的,所以它的原生类为空,要想使用可以自定义
source.prototype = new Object;
source.prototype.c=true;
//注意,这里无法访问到b
source.prototype.y=function(){alert(this.b);}
//可以访问到c,要想访问b要通过source
source.prototype.z=function(){alert(this.c + source.b);}
//由此可知道this在这里是指向prototype的

 

/*
//把上面的代码换成如下:
source.prototype = new function(){
this.a=90;
this.y=function(){alert(this.b);};
this.c=false;
}
//会发现测试结果都是一样的,理由很简单,function继承了Object!
//其实很好理解,已经定义好了的对象怎么可以再让它随便具有继承特性?
//就算让它有了原生对象,也只能变为一个特殊的属性,当然属性值就是这个原生对象了
//后面会看到如果是一个类继承了一个原生对象(注意!不是继承类)
//那么这个原生对象里的所有属性和方法都会变成子类对象的属性和方法
*/

/*
//属性
alert(source.a);
alert(source['a']);
alert(source["a"]);
//方法
source.x();
source['x']();
source["x"]();

//下面两种方式都是错误的
//source.y();
//source['y']();

//访问原生对象
alert(source.prototype.c);
source.prototype.z();

//遍历属性和方法
//如果是属性显示值
//如果是方法显示函数体
//如果是原生对象,显示prototype : [Object Object]
for(var p in source)
 alert(p + " : " + source[p]);
*/

 

//对象定义方法二(定义的是类,使用时一定要初始化,当然不初始化语法也不会有错)
var hander = function handleCaller() {//构造函数,里面的语法遵循普通函数
  this.a=8;
    this.calling=function(i){
 alert(i*this.a);
 };
 this.c=7.4;
}
hander.prototype.b = true;
hander.prototype.dosth = function(i){
 //这里就可以访问到a了,也能调用方法,也能访问到b,但是这里的c会被实例化的构造函数里的c所取代
   this.calling(i);
 alert(this.c + '|' +this.b + '-> ' + this.a + ';' + 2*i);
};
hander.prototype.c = 'ok';//会被hander覆盖
hander.prototype.doelse = function(){};

/*
//只是运行构造函数,没实际意义
handleCaller();

//需要实例化,否则无法访问
alert(hander.a);
//hander.calling(2);

//这样就可以了
alert((new hander).a);

//如果在运行前没有new hander的代码,下面的
//匿名对象运行内部成员函数会出错,不知道这是不是IE7的一个bug
//所以合理的做法是先声明一个对象
//new hander;
//(new hander).calling(8);

//匿名运行prototype方法内
//如果有调用内部成员函数也会有同样的问题
//new hander;
//(new hander).dosth(8);

//常规操作
var h = new hander;
alert(h.a);//属性
h.calling(2);//方法
h.dosth(3);//prototype方法

//竟然没有任何属性和方法?
//当然不是了
//千万要记得要实例化哦
//for(var p in hander)
// alert(hander[p]);

//顺序是(原生函数、原生属性按和加入顺序相反的顺序)、(成员函数、成员变量按构造函数的顺序)
//由此我们可以看出通过原生对象可以实现继承
//成员函数、成员变量可以替换父类的函数和属性
//即加载一个对象先是原生、然后是自己的构造函数
//for(var p in new hander)
// alert((new hander)[p]);

var h = new hander
for(var p in h)
  alert(p + " : " + h[p]);
*/
</script>

 

posted on 2007-05-15 23:44  图梦  阅读(342)  评论(0)    收藏  举报