日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

apply和call

發(fā)布時間:2024/9/19 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 apply和call 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

前言

  • apply 和 call 可以改變函數(shù)執(zhí)行時的 this 對象。

舉個例子

<script> class ClassA {constructor() {this.name = 'AA';}show() {console.log(this.name);} }class ClassB {constructor() {this.name = 'BB';} }var a = new ClassA(); var b = new ClassB();a.show(); // output>> AA a.show.call(b); // output>> BB ClassA.prototype.show.call(a); // output>> AA ClassA.prototype.show.call(b); // output>> BBa.show.apply(b); // output>> BB ClassA.prototype.show.apply(a); // output>> AA ClassA.prototype.show.apply(b); // output>> BB </script>
  • a.show() 這里執(zhí)行時,this 是你認為的 this 。
  • a.show.call(b)、a.show.apply(b)執(zhí)行時, this 變成了 b 。
  • ClassA.prototype.show.call(a)、ClassA.prototype.show.call(b)、ClassA.prototype.show.apply(a)、ClassA.prototype.show.apply(b),傳啥啥是this。
  • 總結一下:通過 apply 和 call 改變了 show 執(zhí)行時的 this 。

函數(shù)定義

/*apply()方法*/ function.apply(thisObj[, argArray]) /*call()方法*/ function.call(thisObj[, arg1[, arg2[, [,...argN]]]]);

從定義可以看出,apply 接受參數(shù)數(shù)組,而 call 需要一個一個的寫上參數(shù)。
嗯,兩個函數(shù)意思是一樣的,只是應用場景不同。

  • 當有了參數(shù)數(shù)組,那就用apply。
  • 當參數(shù)是零散的情況時,那就用call。

參考

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
https://www.cnblogs.com/lengyuehuahun/p/5643625.html
https://www.cnblogs.com/lengyuehuahun/p/5643625.html
https://blog.csdn.net/youlinhuanyan/article/details/108107380

總結

以上是生活随笔為你收集整理的apply和call的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。