六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 158|回复: 0

javascript对象的继承

[复制链接]

升级  38%

27

主题

27

主题

27

主题

秀才

Rank: 2

积分
107
 楼主| 发表于 2013-2-7 20:16:14 | 显示全部楼层 |阅读模式
该篇文章的代码采摘自http://www.cnblogs.com/jingtao/archive/2008/04/29/1175668.html
自己只经过了微小的改动
 
代码主要说明了三种继承javascript对象的方法:apply,复制,prototype
<html><head>    <title>JavaScript面向对象编程</title>    <script language="javascript" type="text/javascript">    //基类    function Person()    {        //定义属性        this.Name="Person";        this.Sex="NONE";        this.Age="?";        //定义方法        this.SayName=function(){alert(this.Name);};        this.SaySex=function(){alert(this.Sex);};        this.SayAge=function(){alert(this.Age);};    }    //子类    function ManPerson()    {           this.Name="ManPerson";        this.Sex="Man";        this.Age="20";        //执行该语句时会调用Person中的构造器,先前赋值的ManPerson,Man,20就失去作用了,所以这句话        //要放在this.Name="ManPerson";之前才能即继承Person的方法,又不会覆盖我们的赋值操作。        Person.apply(this);    }        //第一种方法    function first(){    var p = new Person();    //执行结果为Name:Person  Sex:NONE  Age:?    alert("Name:"+p.Name+"  Sex:"+p.Sex+"  Age:"+p.Age);    //执行结果Person    p.SayName();    var mp=new ManPerson();    //apply在赋值后结果为:Name:Person  Sex:NONE  Age:?    //在赋值前结果为:Name:ManPerson  Sex:Man  Age:20    alert("Name:"+mp.Name+"  Sex:"+mp.Sex+"  Age:"+mp.Age);    //执行结果Man    //可以看到ManPerson很好的继承了Person    mp.SaySex();    }        //第二种方法    function second(){    for(pro in Person)    {        ManPerson[pro]=Person[pro];    }    var p=new Person();    //执行结果为Name:Person  Sex:NONE  Age:?    alert("Name:"+p.Name+"  Sex:"+p.Sex+"  Age:"+p.Age);    //执行结果Person    p.SayName();    var mp=new ManPerson();    //执行结果为Name:Person  Sex:NONE  Age:?    alert("Name:"+mp.Name+"  Sex:"+mp.Sex+"  Age:"+mp.Age);    //执行结果NONE    mp.SaySex();    mp.Name="ManPerson";    //执行结果:ManPerson    //可以看到ManPerson继承了Person的SayName    mp.SayName();        }    //第三种方法    function third(){    //第三种方法    ManPerson.prototype=Person.prototype;    var mmp=new ManPerson();    //执行结果:Person    mmp.SayName();    mmp.Name="ManPerson";    //执行结果:ManPerson、    //ManPerson继承了Person的方法    mmp.SayName();    }    </script></head><body>    <form id="form1" runat="server">    <div>    <button value="FirstMethod" >FirstMethod</button><br />    <button validationgroup="SecondMethod" >SecondMethod</button><br />    <button value="ThirdMethod" >ThirdMethod</button>    </div>    </form></body></html> 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表