Yesterday just did Ali's front-end online pen question, which has a blank question as follows
function func () { alert (this. valueOf ()); } func._________; // expected result is ABC
When I first saw this, I thought of the call () and the Apply () method, but the use of the two methods only had a vague memory.
So, for this problem, their own use of call () and apply () for further information and understanding, this record in order to deepen the impression, but also easy to find later.
Role:
Calls a function in a specific scope. That is, set the value of the This object in the function body.
Usage:
Both call () and apply () accept two parameters: one is the scope in which the function is run, and the other is the passed parameter.
The main difference between the two is that they receive parameters in different ways. where call () receives parameters, the parameters must be listed one at a time, and the parameter received by apply () must be an array of parameters, either an instance of an array or an arguments object. For example:
functionsum (num1,num2) {returnnum1+num2;} functionApplySum1 (num1,num2) {returnSum.apply ( This, arguments);//incoming Arguments Object}functionapplySum2 (num1,num2) {returnSum.apply ( This, [num1,num2]);//Incoming Array}functionCallsum (num1,num2) {returnSum.call ( This, num1,num2);//The incoming parameters are listed}
Whether you use call () or apply () depends entirely on what kind of method you take to pass parameters to the function.
So the answer to the blanks in the beginning is not the only one, here are the following two kinds:
Func.call ("abc"); Func.apply ("abc");
Call () and apply () in JavaScript