javascript 中 call apply 方法的區別

來源:互聯網
上載者:User

標籤:

function foo(arg1, arg2, arg3){

alert(art1 + arg2 + arg3);

}



foo.call(this, arg1,arg2,arg3) == foo.apply(this, arguments) == this.foo(arg1, arg2, arg3)


call , apply 都屬於 Function.prototype的一個方法, 它是JavaScript引擎內在實現的, 因為屬於 Function.prototype 

所以每個Function對象執行個體,也就是每個方法都有call , apply 屬性.  

兩個方法容易混淆,因為它們作用一樣,只是使用方式不一樣.


相同點: 兩個方法的作用完全一樣

不同點:方法傳遞的方式不一樣.


對於foo.call(this, arg1, arg2, arg3)


foo是一個方法,this是方法執行時上下文相關對象,arg1, arg2, arg3是傳給foo方法的參數.這裡所謂的方法執行時上下文相關對象, 如果有物件導向的編程基礎,那很好理解,就是在類執行個體化後對象中的this.

在JavaScript中,代碼總是有一個內容物件,代碼處理該對象之內. 內容物件是通過this變數來體現的, 這個this變數永遠指向當前代碼所處的對象中.


下面一個例子,理解!

<script type="text/javascript">function print(arg1,arg2,arg3){alert(arg1 + ‘ - ‘+arg2+‘ - ‘ + arg3)}function example(a, b, c ){//call 方式print.call(this,a,b,c);//apply 方式,參數作為數組傳遞, 可以直接使用JavaScript方法內本身有的arguments數組print.apply(this,arguments);//封裝成數組print.apply(this,[a,b,c]);}</script><input type="button" value="test" onclick="example(‘wang‘,‘ting‘,‘tttt‘)" />


彈出了3次




javascript 中 call apply 方法的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.