转载: http://www.cnblogs.com/silence516/articles/1509456.html
JS- 封装、继承、多态
Javascript是一门解释型的语言,是基于对象的,并不是真正的面向对象的语言,对变量类型的应用也是宽松的,其实它同样可以模拟面向对象的功能:
JS- 封装、继承、多态
Javascript是一门解释型的语言,是基于对象的,并不是真正的面向对象的语言,对变量类型的应用也是宽松的,其实它同样可以模拟面向对象的功能:
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);//输入错啦.