Introduction to the function of the four call pattern, we first to understand the concept of functions and methods, in fact, functions and methods are essentially the same, that is, the name is not the same. Function: If a function is related to any object, it is called the function. Method: If a function exists as an object property, we call it a method. The next step is to start the subject today. 1, function call mode. is called by function, the specification is: function fn () {} fn (); The pointer to this in the function->window. The cases are as follows:
var age = 38; var obj = { age: 18, getAge: function() { function foo() { console.log(this.age); // 因为是函数调用模式,所以this指向window全局变量,所以输出为38 } // 只看这个函数是怎么调用,不管函数是在哪声明的! foo(); } }; obj.getAge();
2, method invocation mode. is called by the properties of the object, and the canonical notation is:
var obj = { say: function() { console.log(this); } }; obj.say();
The current object, which is the point of this in the function. The cases are as follows:
var age = 38; var obj = { age: 18, getAge: function() { console.log(this.age);// 18 } }; obj.getAge();//因为是方法调用模式,this指向当前的对象obj。
3, the constructor mode if it is called as a constructor, then this is the point to: New object created! The canonical wording is:
function foo() { this.name = "123"; } var f0 = new foo(); 没有找到合适的案例,为大家见谅!!!
4, Function context (borrowing method mode). The point of this in context mode is not the same as the first three modes, and its this point can be changed, while the first three modes are fixed. The function context is the function scope I understand. Basic syntax: Both apply and call are followed by the same two parameters as apply and the first parameter: the use of that object to invoke the function; Apply the second argument is: An array or a pseudo-array, the value of the array as a function parameter is passed in ; Call the second parameter is: is the base data type (number string Boolean), and the case is as follows:
//1:求一个数组中的最大值 方法一:常规写法 var arr = [9, 1, 4, 101, 7, 22, 8]; var maxNum = arr[0], i = 1, len = arr.length; for(; i < len; i++) { if(arr[i] > maxNum) { maxNum = arr[i]; } } console.log(maxNum); 方法二:使用上下文调用模式(apply); var arr = [9, 1, 4, 101, 7, 22, 8]; var maxNum=Math.max.apply(window,arr);//Math.max是window中的排序方法我们可以通过apply借用window中Math.max方法来对数组进行排序。 console.log(maxNum);
A detailed description of the four invocation patterns of functions in JavaScript