UED TEAM

我们的团队博客

登录 | RSS | 收藏本站
08-11
27

javascript的封装、继承、多态

作者:mike 日期:08-11-27 时间:6:28 下午

Javascript是一门解释型的语言,是基于对象的,并不是真正的面向对象的语言,对变量类型的应用也是宽松的,其实它同样可以模拟面向对象的功能:

function myfun1(){
//这是私有属性
var private1 = “这是私有属性”;
var privateMethod = function(){
alert(private1);
}
//这是实例属性
this.publicvar = “这是实例属性”;
this.public1 = function(){
privateMethod();
}
}

var newfun1 = new myfun1();
newfun1.public1(); //这是私有属性
alert(newfun1.publicvar);//这是实例属性
alert(newfun1.private1); // undefined
//newfun1.privateMethod(); //运行错误

function myfun2(){

}
myfun2.staticvar = “这是静态属性”;
myfun2.staticmethod = function(){
alert(myfun2.staticvar);
}

var newfun2 = new myfun2();
//newfun2.staticmethod();//运行错误;
alert(newfun2.staticvar);//undefined

//静态私有成员
var myfun3 = (function(){
function privateProperty(){

}
privateProperty.staticvar = “这是静态私有成员”;
privateProperty.staticmethod = function(){
alert(privateProperty.staticvar);
}
privateProperty.staticmethod();
return privateProperty
})();*/

//静态类
var funcount = 0;
var myfun4 = new function(){
funcount++;
this.printCount = function(){
alert(funcount);
}
}
myfun4.printCount(); //输出1;
myfun4.printCount(); //输出1;

myfun4.prototype.amethod = function(){
alert(“原型对象”);
}//运行错误
var newfun4 = new myfun4();
newfun4.amethod();

//运行错误,说明myfun3创建并实例化之后就不能再为它添加方法,属性
new myfun3.constructor().printCount();//如果你确实想实例化,这样也可以.

//原型继承
var myfun5 = function(){

}
myfun5.prototype.myfun5_extend = function(){
alert(“这是原型继承的”);
}
var myfun5_sub = function(){

}
myfun5_sub.prototype = new myfun5();
var newfun5 = new myfun5_sub();
newfun5.myfun5_extend(); //这是原型继承的

//调用继承
var myfun6 = function(){
this.method_p = function(){
alert(“这是调用继承的”);
}
}
var myfun6_sub = function(){
myfun6.call(this);
}

var newfun6 = new myfun6_sub();
newfun6.method_p();//这是调用继承的

//覆盖
var myfun7 = function(){
this.method = function(){
alert(“这是父对象方法”);
}
}
var myfun7_sub = function(){
this.method = function(){
alert(“这是子对象方法”);
}
}
myfun7_sub.prototype = new myfun7();
var newfun7 = new myfun7_sub();
newfun7.method(); //这是子对象方法,父对象方法被覆盖了.

//多态
function myfun8(a,b){
var a = a;
var b = b;
if( typeof a == “number” && typeof b == “number” ){
alert( a * b );
}
else if( typeof a == “string” && typeof b == “string” ){
alert( a + b );
}else{
alert( “输入错啦” );
}
}
myfun8(3,4); // 输出12;
myfun8(“hi,”,”你好”);//输出hi,你好;
myfun8(“hi”,5);//输入错啦.

Tags:

相关文章

随机文章

javascript的封装、继承、多态 评论 (4)

  • RYErnest

    Nice post u have here :D Added to my RSS reader

  • didi

    赞,现在水平不足,只能看懂前半部分,学习……

  • 菜鸟飞啊飞

    啧..静态私有成员和静态类..有点迷糊.

  • Michael

    文章貌似写的有点乱吧 注释的位置都不太对

发表评论

评论只需审核一次,以后网友可以继续使用原来ID,邮箱进行回复:)