JS OOP编程
//父类 function BaseFun() { var hello = "HelloWorld"; this.HelloPublic = "Hello--World"; var privatefun = function () { alert("hellow"); } this.publicfun = function () { var a = this.HelloPublic; alert("this is public funtion" + a); } } //子类 function SubFun() { BaseFun.apply(this, arguments);// 建立继承关系 this.SubHello = function () { alert("sub ok"); } } //动物基类 function BaseAnimal() { this.Type = "Animal"; this.Eat = function () { alert(this.Type + "会吃东西方法"); } this.Walter = function () { alert(this.Type + "喝水"); } } //猪子类 function Pie() { //子类方法覆盖父类方法 this.Eat = function (arg) { alert(arg); } } //狗子类 function Dog() { } //prototype属性,指定为该属性的值,该构造器的实例对象自动继承 Dog.prototype={ eatfood:function () { alert("吃东西"); }, sleep:function () { alert("睡觉"); } };
function getFun() { var basef=new BaseFun(); var a=basef.HelloPublic; basef.HelloPublic="我是父类"; basef.publicfun(); var sub=new SubFun(); sub.HelloPublic="我是子类"; sub.publicfun(); var pie=new Pie(); pie.Eat("吃东西"); //建立继承关系 Pie.prototype=new BaseAnimal(); var p=new Pie(); p.Type="猪"; p.Walter(); var dog=new Dog(); dog.sleep(); dog.eatfood(); }