码迷,mamicode.com
首页 > Web开发 > 详细

JS继承几种方式

时间:2017-11-08 13:22:26      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:使用   数列   new   lov   简单   方式   关系   共享   实例   

1、原型继承
<script>
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function(){
alert("使用原型得到Name:"+this.name);
}
var per = new Person("dzk",21);
per.sayHello();//输出:使用原型得到Name:dzk

function Student(){}
Student.prototype = new Person("gw",22);
var stu = new Student();
Student.prototype.grade = 5;
Student.prototype.intr=function(){
alert(this.grade);
}
stu.sayHello();//输出:使用原型得到Name:gw
stu.intr();//输出:5
</script>
优点:
1、非常纯粹的继承关系,实例是子类是实例,也是父类的实例,如上stu
2、父类新增原型方法or原型属性,子类都能访问到
3、简单、易于实现
缺点:
1、无法实现多继承
2、来自原型对象的引用属性是所有实例共享的

2、构造函数继承
<script>
function Parent(name){
this.names = name;
this.sayParent=function(){
alert("Parent:"+this.names);
}
}
function Child(name,age){
this.tempfds = Parent;
this.tempfds(name);
this.age = age;
this.sayChild=function(){
alert("Child"+this.names+"age:"+this.age);
}
}

var parent=new Parent("江剑臣");    
parent.sayParent(); //输出:“Parent:江剑臣”  
    var child=new Child("李鸣",24);
    child.sayChild();  //输出:“Child:李鸣 age:24”  
</script>
优点:
1、解决了1中,子类实例共享父类引用属性的问题
2、可以实现多继承
缺点:
1、实例并不是父类的实例,只是子类的实例
2、无法实现函数复用,每个子类都有父类实例函数的副本,影响性能

3、Call、apply实现继承
<script>
function Person(name,age,love){
this.name = name;
this.age = age;
this.love = love;
this.say=function(){
  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>

JS继承几种方式

标签:使用   数列   new   lov   简单   方式   关系   共享   实例   

原文地址:http://www.cnblogs.com/xiaoweigogo/p/7803214.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!