當前位置:
首頁 >
apply和call
發布時間:2024/9/19
49
豆豆
生活随笔
收集整理的這篇文章主要介紹了
apply和call
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
- apply 和 call 可以改變函數執行時的 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() 這里執行時,this 是你認為的 this 。
- a.show.call(b)、a.show.apply(b)執行時, 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 執行時的 this 。
函數定義
/*apply()方法*/ function.apply(thisObj[, argArray]) /*call()方法*/ function.call(thisObj[, arg1[, arg2[, [,...argN]]]]);從定義可以看出,apply 接受參數數組,而 call 需要一個一個的寫上參數。
嗯,兩個函數意思是一樣的,只是應用場景不同。
- 當有了參數數組,那就用apply。
- 當參數是零散的情況時,那就用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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: javascript 函数 有任意多个参
- 下一篇: 【若依(ruoyi)】swagger 生