1. 程式人生 > >js使用prototype,call/apply實現繼承

js使用prototype,call/apply實現繼承

1、原型方式

  • 可以動態的給所需物件設定屬性和方法 ;
  • 子類繼承父類,可以使用和享有父親的所有屬性和方法。
<html>  
<body>  
<script type="text/javascript">  
    function Person(name,age){  // 父類
        this.name=name;  //父類的私有屬性
        this.age=age;  
    }  
    Person.prototype.sayHello=function(){  //用處1,動態的給父類Person增加sayHello方法
        alert("使用原型得到Name:"+this.name);  
    }  
    var per=new Person("馬小倩",21);  
    per.sayHello(); //輸出:使用原型得到Name:馬小倩  

--------------------------------------------- 
      
    function Student(){}  //當做子類
    Student.prototype=new Person("洪如彤",21);  //用處2:子類Student繼承父類Person的所有方法和屬性
    var stu=new Student();  //然後建立子烈的例項
    Student.prototype.grade=5;  //再給子類動態新增grade屬性
    Student.prototype.intr=function(){  //再給子類動態新增intr方法
        alert(this.grade);  
    }  
    stu.sayHello();//使用原型得到Name:洪如彤 。使用從父類繼承的sayHello()方法   
    stu.intr();//5  。使用給子類動態新增的intr方法
</script>  
</body>  
</html>

2、call和apply:

先看下語法

obj.call(thisObj, arg1, arg2, ...);
obj.apply(thisObj, [arg1, arg2, ...]);

解釋:把obj的this繫結到thisObj上,這時候thisObj具備了(或者說繼承了)obj的屬性和方法,然後在thisObj的執行環境裡面執行obj的屬性和方法,繫結後會立即執行函式。

  • apply和call 本來就是為了擴充套件函式的作用域而生的,換句話說就是為了改變this的指向存在的
  • 當一個object沒有某種方法,但是其他的有,我們可以藉助call和apply來用其他物件的方法來做操作,也可以傳引數
<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){  // 可以理解為在student的執行環境裡執行person的屬性和方法
        Person.call(this,name,age);  
    }  

    //apply方式  
    function teacher(name,love){   //可以理解為在student的執行環境裡執行person的屬性和方法 
        Person.apply(this,[name,love]);  
        //Person.apply(this,arguments); //跟上句一樣的效果,arguments  
   //  Print.apply(this,arguments);  //還可以實現繼承多個父類,但是原型 prototype只能繼承一個父類!!!切記
    }  

    

    var per=new Person("武鳳樓",25,"魏熒屏"); //輸出:“武鳳樓”  
    per.say();  
    var stu=new student("曹玉",18);//輸出:“曹玉”  
    stu.say();  
    var tea=new teacher("秦傑",16);//輸出:“秦傑”  
    tea.say();  

</script>  
</body>

總結:

1)call和apply可以實現多繼承,一個子類可以繼承多個父類,但是prototype只能有有一個父類;

2)call和apply,可以膚淺理解為在子執行環境中執行父類的方法和屬性;

3)prototype可以動態的給物件增加屬性和方法;