首页 > 代码库 > JavaScript面向对象(3)--prototype和继承

JavaScript面向对象(3)--prototype和继承

1、使用prototype实现继承 

 1 function BaseClass() 2 { 3     var privateName = "private"; 4      5     this.pubicName1 = "public1"; 6      7     var privateMethod = function() 8     { 9         alert("privateMethod");10     }11     12     this.publicMethod1 = function()13     {14         alert("publicMethod1");15     }16     17     this.alertPrivateName = function()18     {19         alert(privateName);20         privateMethod();21     }22     23 }24 25 BaseClass.prototype.publicName2 = "public2";26 BaseClass.prototype.publicMethod2 = function()27 {28     alert("publicMethod2");29 }30 31 BaseClass.staticName = "static";32 BaseClass.staticMethod = function()33 {34     alert("staticMethod");35 }36 37 MyClass = function()38 {39     this.getName = function()40     {41         //无法访问基类的私有属性和方法42         alert(privateName);43         privateMethod();44     }45 }46 47 MyClass.prototype = new BaseClass();48 object = new MyClass();49 50 //可以访问基类公有属性51 alert(object.pubicName1);52 alert(object.publicName2);53 //可以访问基类静态属性54 alert(object.constructor.staticName);55 //可以访问基类公有方法56 object.publicMethod1();57 object.publicMethod2();58 //可以访问基类静态方法59 object.constructor.staticMethod();60 //可以通过基类公有方法访问基类的私有属性和方法61 object.alertPrivateName();

 

MyClass.prototype = new BaseClass()实现了MyClass对BaseClass的继承。MyClass可以访问基类的公有属性、静态属性、公有方法、静态方法,还能够通过基类的公有方法间接访问基类的私有属性和方法。非常完美的继承不是吗!

 

2、使用me实现继承

function BaseClass(){    var privateName = "private";        this.pubicName1 = "public1";        var privateMethod = function()    {        alert("privateMethod");    }        this.publicMethod1 = function()    {        alert("publicMethod1");    }        this.alertPrivateName = function()    {        alert(privateName);        privateMethod();    }    }BaseClass.prototype.publicName2 = "public2";BaseClass.prototype.publicMethod2 = function(){    alert("publicMethod2");}BaseClass.staticName = "static";BaseClass.staticMethod = function(){    alert("staticMethod");}MyClass = function(){    var me = new BaseClass();        me.getName = function()    {        //无法访问基类的私有属性和方法        alert(privateName);        privateMethod();    }        // 定义子类的公有方法    me.otherMethod = function()    {        alert("otherMethod");    }        return me;}

  // 通过Prototype定义的方法,无法访问
  MyClass.prototype.otherMethod2 = function()
  {
    alert("otherMethod2");
  };

object = new MyClass();//可以访问基类公有属性alert(object.pubicName1);alert(object.publicName2);//可以访问基类静态属性alert(object.constructor.staticName);//可以访问基类公有方法object.publicMethod1();object.publicMethod2();//可以访问基类静态方法object.constructor.staticMethod();//可以通过基类公有方法访问基类的私有属性和方法object.alertPrivateName();

 

 这种继承方式的效果基本和第一种一样,但是需要注意这种继承方式只能够通过在函数体内部对me增加属性和方法,无法使用prototype的方式,因为在new MyClass()的时候返回的其实是增加了属性和方法的me,MyClass只是一个壳而已。

 

JavaScript面向对象(3)--prototype和继承