javascript面向对象特性代码实例
一、基本的类的使用
方法一:
functionsth(a)//构造函数
{
this.a=a;
this.fun=output;//成员函数
}
functionoutput(a,b,c)
{
document.write(this.a);
}
//调用
vars=newsth(250);
s.fun(1,2,3);
ouput(1,2,3);//如果output在sth之前就是错的
方法二:
{
this.a=a;
this.output=function()
{
document.write(this.a);
}
}
vars=newsth(2);
s.output();//输出2
二、继承
方法一:
{
this.x=x;
}
functionB(x,y)
{
//方法1
/*
this.construct=A;
this.construct(x);
deletethis.construct;
*/
//方法2
//A.call(this,x);
//方法3
A.apply(this,newArray(x));//亦可A.apply(this,arguments),不过arguments参数顺序一定要对
this.y=y;
this.print=function()
{
document.write("x=",x,
",y=",y);
}
}
varb=newB(1,2);
b.print();
alert(BinstanceofA);//输出false
优点:可以实现多继承(多调用call就好)
缺点:
·必须以构造函数方式使用
·使用instanceof运算符运算此类继承结果为false
方法二:
{
}
A.prototype.x=1;
functionB()
{
}
B.prototype=newA();//不能带参数!
B.prototype.y=2;
B.prototype.print=function()
{
document.write(this.x,",",this.y,"<br>");
}
varb=newB();
b.print();
document.write(binstanceofA);//输出true
缺点:
·不能实现多继承
·构造函数不带参数
Tips
通常使用混合模式,两者一起用
functionA(x)
{
this.x=x;
}
A.prototype.printx=function() //写到A类里面this.printx=function....也是可以的,下同
{
document.write(this.x,"<br>");
}
functionB(x,y)
{
A.call(this,x);
this.y=y;
}
B.prototype=newA();//不能带参数!
B.prototype.printxy=function()
{
document.write(this.x,",",this.y,"<br>");
}
varb=newB(1,2);
b.printx(); //输出1
b.printxy();//输出1,2
document.write(binstanceofA);//输出true
三、类似静态成员函数的使用
{
this.a=a;
}
sth.fun=function(s)
{
document.write(s.a);
}
vars=newsth(2);
sth.fun(s);//输出2
四、对象的释放
obj=null;//取消引用,会自动进行垃圾回收;如果需要根本释放此对象,要将它的所有引用都赋值为null
五、函数对象
v(1,2);//将会输出3
六、回调函数
{
func(arg);
}
functionfun(arg)
{
document.write(arg);
}
//callback(func,"sb");//这种做法不行
varfunc=newFunction("arg","fun(arg);");
//当然也可以把func(arg)换成具体的执行代码,
//但是函数代码庞大了就最好这样做了
callback(func,"sb");
七、函数的重载
{
switch(arguments.length)
{
case1:
document.write(arguments[0]);
break;
case2:
document.write(arguments[0]+arguments[1]);
break;
default:
document.write("ERROR!");
break;
}
}
fun(1);
fun(1,2);
八、利用函数闭包实现有“静态变量”的函数
{
varv=1;
functionfun2()
{
++v;
document.write(v);
document.write("<br>");
returnv;
}
returnfun2;
}
varfunc=fun();
func();//输出2
func();//输出3
func();//输出4
相关文章
- JavaScript验证手机号码代码简单代码实例详解编程语言
- JavaScript验证字符串是否包含英文字符、数字或者汉字代码实例详解编程语言
- JavaScript学习总结(九)——Javascript面向(基于)对象编程详解编程语言
- 使用javascript访问XML数据的实例
- javascript三组文字间隙滚动实例代码
- JavaScript给汉字排序实例代码
- JavaScript读取图片实例代码
- javascript中的继承实例代码
- JavaScript实现类的多种方法实例
- 原生javascript兼容性测试实例
- javascript实现TreeView无刷新展开的实例代码
- JavaScript获取/更改文本框的值的实例代码
- javascript:文字不间断向左移动的实例代码
- Javascript事件实例详解
- JavaScript实现鼠标拖动元素实例代码
- javascript移动设备Web开发中对touch事件的封装实例
- javascript实例分享---具有立体效果的图片特效
- 一个JavaScript获取元素当前高度的实例
- JavaScript删除指定子元素代码实例
- Javascript中3种实现继承的方法和代码实例
- 一个JavaScript去除字符串末尾的空白实例代码