探究call 和 apply 的原理
生活随笔
收集整理的這篇文章主要介紹了
探究call 和 apply 的原理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
建議看這片文章時可以點擊音樂?,來個單曲循環,美滋滋
我的博客內容更精彩,好東西需要耐心等待哦!?
先拿call開刀
作用:call和apply都是替換函數內錯誤的this var a = {value:1}var b = function(){console.log(this.value) // 如果不對this進行綁定執行bar() 會返回undefined}b.call(a) //1去除繁瑣的講解,一步到位自己模擬call的用法寫一個函數,達到相同目的
Function.prototype.myCall = function(context){var context = context || window; //當沒傳入值時候,就是指全局windowcontext.fn = this; //把調用myCall前的方法緩存下來var args = [...arguments].slice(1);//使用...打散傳入值,并去除第一方法,得到一個數組var result = context.fn(...args);//把數組打散,把dinging 18傳入b方法中delete context.fn; //刪除return result}var a = {value:1}var b = function(name,age){console.log(this.value)console.log(name)console.log(age)}b.myCall(a,"dingding",18)apply
apply的方法和 call 方法的實現類似,只不過是如果有參數,以數組形式進行傳遞apply這個API平時使用的場景,代碼如下:
var a = {value:1}var b = function(name,age){console.log(this.value)console.log(name)console.log(age)}b.apply(a,["dingding",18])直接上模擬apply功能代碼
Function.prototype.myApply = function(context){var context = context || window;context.fn = this;var result;if(arguments[1]){result = context.fn(...arguments[1]) }else{result = context.fn()}delete context.fnreturn result}var a = {value:1}var b = function(name,age){console.log(this.value)console.log(name)console.log(age)}b.myApply(a,["dingding",18])參考資料
總結
以上是生活随笔為你收集整理的探究call 和 apply 的原理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 推荐您使用 Markdown 来编辑文章
- 下一篇: NexT 高级配置