apply和call
生活随笔
收集整理的這篇文章主要介紹了
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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: javascript 函数 有任意多个参
- 下一篇: 中国电信发布千亿参数“星辰”大模型:12