標籤:繼承 app 樣本 函數調用 call 代碼 需要 bsp java
前段時間在使用javascript的過程中遇到了繼承的問題,自己順便就對call()和apply()方法進行了瞭解。
兩個方法的共同之處:這兩個方法作用相同,都用來改變當前函數調用的對象,即改變this的指向。
兩個方法的不同之處:不同之處就是兩種方法的傳參方式不同,apply接受的是數組參數,call接受的是連續參數。
apply()方法的定義:
Function.apply(obj,args);
obj:這個對象會代替Function類裡邊所指向的this對象。
args:這是一個數組,作為參數傳遞給Function。
樣本:
<script> function Intro(name,age){ this.name=name; this.age=age; this.speak=function(){ console.log(‘My name is ‘+this.name+‘.‘+‘ I am ‘+this.age+‘ years old.‘); } } function IntroInh(name,age){ Intro.apply(this,arguments); } var lm=new IntroInh(‘LiMing‘,20); lm.speak();</script>
上面的代碼做了一個簡單的繼承應用,也展示了apply()在其中的作用。
call()方法的定義:
Function.call(obj,[param1[,param2[,…[,paramN]]]]);
obj:這個對象會代替Function類裡邊所指向的this對象。
params:這是一個參數列表。
樣本:
<script> function Intro(name,age){ this.name=name; this.age=age; this.speak=function(){ console.log(‘My name is ‘+this.name+‘.‘+‘ I am ‘+this.age+‘ years old.‘); } } function IntroInh(name,age){ // Intro.apply(this,arguments); Intro.call(this,name,age);//對比上面apply()的不同; } var lm=new IntroInh(‘LiMing‘,20); lm.speak();</script>
這裡只做一個簡單的概念和應用方法的敘述,具體的項目應用還需要我們進一步的實踐。
關於javascript中call()和apply()方法的總結