来自酷炫的 CNodeMD
首先講解一下Function.apply的原理,再講解一下apply和call的區別 Function.apply是用來設置this的對象 舉個例子
// 全局變量 var avgScore = 0 const avg = list => { // 求和 let sum = list.reduce( (acc, cur) => acc + cur ) // 這裡的this對象會是全局,除非我們用call或者apply來重設this的對象 this.avgScore = sum / list.length } var studentA = { scores: [ 20, 30, 40 ], avgScore: null } // 這裡的函數調用只會影響全局變量avgScore,而不是studentA這個object裡面的avgScore avg(studentA.scores) console.log(window.avgScore) // 30 console.log(studentA.avgScore) // null // 重置全局變量為0 avgScore = 0 // 這裡的call就把函數avg裡面的this對象,改為從全局到stduentA avg.call(studentA, studentA.scores) console.log(window.avgScore) // 0 全局變量沒有變 console.log(studentA.avgScore) // 30 studentA的avgScore變量就改變了
apply和call的區別是第二個參數的表達不一樣 Function.apply(null, [ a, b, c … ]) // 是一個list Function.call(null, a, b, c …) //多個參數 至於原理就都一樣,都是用來設this的對象
最大的好處就是函數借用
// aListLikeObj本來沒有reverse的方法 let aListLikeObj = { 0: "Ironman", 1: "Spiderman", 2: "Thor", 3: "Hulk", length: 4 } // 利用call把Array裡面的reverse函數用在aListLikeObj console.log( Array.prototype.reverse.call(aListLikeObj) ) // { 0: "Hulk", 1: "Thor", 2: "Spiderman", 3: "Ironman", length: 4 }
CNode 社区为国内最专业的 Node.js 开源技术社区,致力于 Node.js 的技术研究。
首先講解一下Function.apply的原理,再講解一下apply和call的區別 Function.apply是用來設置this的對象 舉個例子
apply和call的區別是第二個參數的表達不一樣 Function.apply(null, [ a, b, c … ]) // 是一個list Function.call(null, a, b, c …) //多個參數 至於原理就都一樣,都是用來設this的對象
最大的好處就是函數借用