The call() method and the apply() method are not used a lot in the upper layer applications, but they are often seen when writing JS frameworks at the bottom layer. Then, after a while, Brother Gu of Duniang found that many masters wrote their own understanding and notes, but they were still in a fog, so they went to W3C to study.
When studying these two methods online in W3C, I saw a word called "object impersonation". I think this concept is quite important, which makes me more intuitive to understand these two methods.
Call() method, see the example given by the official
function saysColor(sPrefix,sSuffix) { alert(sPrefix + this.color + sSuffix);};var obj = new Object();obj.color = "blue";sayColor.call(obj, "The color is ", "a very nice color indeed.");The final output is "The color is blue, a very nice color indeed."
Call() method is to replace this in the method with the first parameter, and then pass the following parameters into the method to use
apply() method, let's first look at the example given by the official
function saysColor(sPrefix,sSuffix) { alert(sPrefix + this.color + sSuffix);};var obj = new Object();obj.color = "blue";sayColor.apply(obj, new Array("The color is ", "a very nice color indeed."));The final output still looks like "The color is blue, a very nice color indeed."
In fact, the call() method and the apply() method can be roughly considered to be similar. The first parameter is the replacement of this keyword in the method, but the arguments passed to the method are different. Call is a direct correspondence, and apply is an array that corresponds one by one in the array.
The above understanding of call() and apply() in JavaScript is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.