There are four
1
The function call pattern is the most common and the simplest
// declare a function and call function func() { console.log("Hello World"); } func(); //The output is Hello World or write it like this // Define the function using the function's lambda expression, then call var func = function () { console.log("Hello, Gao Fan"); }; func(); //The output is hello, Gao Fan //In javascirpt, functions can be defined using arrow syntax ("=>"), sometimes called "lambda expressions".
2
method call pattern
After assigning a function to a member of an object, then this is no longer called a function but should be called a method
// define a function var func = function () { console.log("I am?"); }; // assign it to an object var o = {}; o.fn = func; // don't add parentheses here // transfer o.fn (); // output am I?
o.fn is a method, not a function
3
Constructor Pattern
In general function mode, this refers to window; in object method mode, this refers to the current object. In addition to these two cases, functions in JavaScript can also be constructors. The use of functions as a constructor pattern is to add a new in front of the function call
// define a constructor var Person = function () { this.name = "China"; this.sayHello = function() { console.log("Hello" + this.name); }; }; // call the constructor to create the object var p = new Person (); // user target audience p.sayHello(); // output is hello China
First create a constructor Person, then use the constructor to create the object p. The new syntax is used here. Then call the sayHello() method using the object
4
apply call mode
The apply pattern can be used either like a function or like a method
function name.apply(object, parameter array)
1. Create two new js files, "js1.js" and "js2.js";
2. Add code
// in js1.js file var func1 = function () { this.name = "Gao Fan"; }; func1.apply(null); console.log(name); // js2.js file var func2 = function() { this.name = "Programmer"; }; var o = {}; func2.apply(o); console.log(o.name);
Use the apply mode to control the meaning of this arbitrarily
There are four modes of function call in js, namely: functional, method, constructor and apply. In these modes, the meaning of this is: in the function this is the global object window, in the method this Refers to the current object. In the constructor, this is the object to be created. In the apply mode, this can be arbitrarily specified. In the apply mode, if you use null, it is the function mode, and if you use the object, it is the method mode.