First, function definition
1. Function declaration
function Add (i,j) { return i+j; }
Features: 1, function declaration defines the function to be pre-placed. To know when the JS code execution, there will be a pre-parsing, pre-parsing the variable declaration, function declaration ahead of time. 2. When a function declaration is defined repeatedly, it is executed with the last definition, that is, the previous function declaration is overwritten later.
2. Function expression
var function (i,j) { return i+j; }
3. Instantiation of functions
var New Function ("I", "J", "Return (I+J)");
Rarely used, not recommended
Features: 1. Function instantiation definition functions can only access local scope and global scope
Second, function call and Difference
1, Function call Mode: Add ();
2, method call mode: Object.add ();
3. Constructor Call Mode: New function (...);
4. Apply Call Mode: Apply is a method on a constructor prototype. It is the function borrowed
Example:
functionPoint (x, y) { This. x =x; This. y =y;}//define a point constructorPoint.prototype.move (x.y) { This. x + =x; This. Y + =y; }varp =NewPoint (0,0);//instantiate a point of PP.move (2,2);varCircle = (X:1, y:1, r:1);//defines a global circle object, but Circle does not have a move method, so you can use apply or call to borrow P's Move method. P.move.apply (Circle, [2,1]);
5, the different function call pattern difference-this
When JS executes, the JS engine adds this and arguments temporary variables to the local scope of the function. The difference between the different invocation patterns is shown on the point of this.
- In function call mode, this points to the Global object window
- Method invocation mode, this points to the caller
- Constructor mode, this points to the constructed object, and if more than one object is constructed, this points to the constructed object
- Apply (call) invocation mode, this points to the first parameter
Study Questions
var mynumber = { 1, function(i) { var function(i) { console.log (this); this. Value +=1; } Helper (i); }} Mynumber.add (1); // 1, the helper function of this point to which object, 2, this code can implement the correct logic 3, how can be modified to achieve the correct logic
Third, function to pass the parameter
1. Pass by value: original type
2. Pass by share: Object type
var count = {a:1,b:1 var addone = (obj) {obj.a +=1; OBJ.B +=1; return obj;} var ret = AddOne (count); Console.log (ret); Console.log (count); // object {a:2, b:2} Object {a:2, b:2}
But it is not yet possible to determine when to pass by reference, because if a reference is passed inside a function to modify an external variable reference, any change Occurs on an external variable, the result of the practice is as follows:
var count = {a:1,b:1}; var function (obj) { = {a:2,b:2}; return obj;} var ret =2, B:21, b:1}
javascript-function Advanced