js中的apply與call的用法與區別

來源:互聯網
上載者:User

標籤:wan   foo   方式   用法   str   efi   實現   ima   存在   

call 和 apply 都是為了改變某個函數運行時的 context 即上下文而存在的,換句話說,就是為了改變函數體內部 this 的指向
call 和 apply二者的作用完全一樣,只是接受參數的方式不太一樣。

方法定義
apply
Function.apply(obj,args)方法能接收兩個參數:

obj:這個對象將代替Function類裡this對象

args:這個是數組或類數組,apply方法把這個集合中的元素作為參數傳遞給被調用的函數。

call

call方法apply方法的第一個參數是一樣的,只不過第二個參數是一個參數列表

在非strict 模式下當我們第一個參數傳遞為null或undefined時,函數體內的this會指向預設的宿主對象,在瀏覽器中則是window

//在非strict 模式下當我們第一個參數傳遞為null或undefined時,函數體內的this會指向預設的宿主對象,在瀏覽器中則是windowvar test = function(){  console.log(this===window);}test.apply(null);//truetest.call(undefined);//true 

用法

1."劫持"別人的方法(個人感覺也是繼承)

//此時foo中的logName方法將被bar引用 ,this指向了barvar foo = {  name:"mingming",  logName:function(){    console.log(this.name);  }}var bar={  name:"xiaowang"};foo.logName.call(bar);//xiaowang

2.實現繼承

function Animal(name){     this.name = name;     this.showName = function(){       console.log(this.name);     }   }    function Cat(name){    Animal.call(this, name);  }    var cat = new Cat("Black Cat");   cat.showName(); //Black Cat

 

js中的apply與call的用法與區別

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.