建議看這片文章時能夠點擊音樂🎵,來個單曲循環,美滋滋javascript
做用:call和apply都是替換函數內錯誤的this
var a = { value:1 } var b = function(){ console.log(this.value) // 若是不對this進行綁定執行bar() 會返回undefined } b.call(a) //1
去除繁瑣的講解,一步到位本身模擬call的用法寫一個函數,達到相同目的git
Function.prototype.myCall = function(context){ var context = context || window; //當沒傳入值時候,就是指全局window context.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的方法和 call 方法的實現相似,只不過是若是有參數,以數組形式進行傳遞
apply這個API平時使用的場景,代碼以下:github
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.fn return 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])
參考資料緩存