javascript实现继承的三种方式

一、原型链继承 

function Parent(){} 
function Child(){} 
Child.prototype = new Parent(); 

通过对象child的prototype属性指向父对象parent的实例,使child对象的实例通过原型链访问到父对象构造所定义的属性、方法等。

二、使用apply、call方法 

js中call和apply都可以实现继承,唯一的一点参数不同,func.call(func1,var1,var2,var3)对应的apply写法为:func.apply(func1,[var1,var2,var3])。

相同点:第一个参数this都一样,指当前对象。

不同点,第二参数不一样,call是一个个的参数列表,apply是一个数组(arguments也可以)

<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>  

三、对象实例间的继承 

原文来自:http://www.jb51.net/article/20431.htm

猜你喜欢

转载自www.cnblogs.com/chenguiya/p/9071173.html