登录  /  注册
首页 > web前端 > js教程 > 正文

javascript中对象继承的三种方式代码实例详解

伊谢尔伦
发布: 2017-07-20 14:56:42
原创
875人浏览过

js中有三种继承方式

1.js原型(prototype)实现继承

<SPAN style="BACKGROUND-COLOR: #ffffff"><SPAN style="FONT-SIZE: 18px"><html>  
<body>  
<script type="text/javascript">  
    function Person(name,age){  
        this.name=name;  
        this.age=age;  
    }  
    Person.prototype.sayHello=function(){  
        alert("使用原型得到Name:"+this.name);  
    }  
    var per=new Person("小倩",21);  
    per.sayHello(); //输出:使用原型得到Name:小倩  
      
    function Student(){}  
    Student.prototype=new Person("如彤",21);  
    var stu=new Student();  
    Student.prototype.grade=5;  
    Student.prototype.intr=function(){  
        alert(this.grade);  
    }  
    stu.sayHello();//输出:使用原型得到Name:如彤  
    stu.intr();//输出:5  
</script>  
</body>  
</html></SPAN></SPAN>
登录后复制

2.构造函数实现继承

<SPAN style="FONT-SIZE: 18px"><html>  
<body>  
<script type="text/javascript">  
    function  Parent(name){  
        this.name=name;  
        this.sayParent=function(){  
            alert("Parent:"+this.name);  
        }  
    }  
    function  Child(name,age){  
        this.tempMethod=Parent;  
        this.tempMethod(name);  
        this.age=age;  
        this.sayChild=function(){  
            alert("Child:"+this.name+"age:"+this.age);  
        }  
    }  
    var parent=new Parent("江剑");  
    parent.sayParent(); //输出:“Parent:江剑”  
    var child=new Child("李鸣",24); //输出:“Child:李鸣 age:24”  
    child.sayChild();  
</script>  
</body>  
</html></SPAN>
登录后复制

3.call , apply实现继承

<SPAN style="FONT-SIZE: 18px"><html>  
<body>  
<script type="text/javascript">  
    function  Person(name,age,love){  
        this.name=name;  
        this.age=age;  
        this.love=love;  
        this.say=function say(){  
            alert("姓名:"+name);  
        }  
    }  
    //call方式  
    function student(name,age){  
        Person.call(this,name,age);  
    }  
    //apply方式  
    function teacher(name,love){  
        Person.apply(this,[name,love]);  
        //Person.apply(this,arguments); //跟上句一样的效果,arguments  
    }  
    //call与aplly的异同:  
    //1,第一个参数this都一样,指当前对象  
    //2,第二个参数不一样:call的是一个个的参数列表;apply的是一个数组(arguments也可以)  
    var per=new Person("凤楼",25,"荧屏"); //输出:“凤楼”  
    per.say();  
    var stu=new student("曹玉",18);//输出:“曹玉”  
    stu.say();  
    var tea=new teacher("秦杰",16);//输出:“秦杰”  
    tea.say();  
</script>  
</body>  
</html></SPAN>
登录后复制

以上就是javascript中对象继承的三种方式代码实例详解的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号