In Javascript, a function is a first-class citizen and is the central object of Javascript. 1. The function is a value and can be used anywhere the value is used. It can be stored in variables, used in expressions, placed in arrays, put in object value pairs, and passed as parameters... SyntaxHighlighter. all ();
In Javascript, a function is a "first-class citizen" and is the central object of Javascript.
1. The function is a value and can be used anywhere the value is used. It can be stored in variables, used in expressions, placed in arrays, placed in object value pairs, passed in functions as parameters, and returned values as functions;
2. A function is an object that can have data attributes, methods, and prototype objects;
3. functions have callable code blocks and multiple call modes. You can create closures and Callbacks. These two programming modes are very powerful.
Code running: Open the chrome browser, tool --- Javascript console.
References:
Javascript: The Good Parts Douglas Crockford
1. The function is a value.
Let's start with the most common function call form!
1. The function is stored in the variable.
First look at a piece of Common Code:
Function numAdd (a, B ){
Return a + B;
}
NumAdd (5, 7 );
In fact, it means:
Var numAdd = function (a, B ){
Return a + B;
}
NumAdd (5, 7 );
Function objects are stored in the variable numAdd, which can be referenced;
2. functions are used in expressions
Var choice = function (boolvar ){
Return boolvar? Function (num) {return num * num}: function (num) {return num/2 ;}
}
Var square = choice (true );
Square (2); // print 4
Var half = choice (false );
Half (4); // print 2
This code returns different function objects based on the passed boolean values. If it is true, it returns a square function. If it is false, it returns a half function. It also demonstrates how a function acts as a return value.
3. Pass the function as a parameter
Var worker = function (callback ){
Var arrparams = [1, 2, 3, 4, 5];
Callback (arrparams );
};
Worker (function (arrparams ){
Document. write (You get me print it! ');
Document. write (arrparams. join (''));
});
Worker (function (arrparams ){
Document. write (You get me print it reversed! ');
Var reversed = arrparams. reverse ();
Document. write (reversed. join (''));
});
As a parameter, a function can be passed into a callback. Callback is a very powerful programming mode. For more information about callback, see programming mode: callback.
4. Functions Act as object value pairs
Var person = {
Name: 'shuqin ',
Say: function (){
Document. write ("I am" + this. name );
}
}
Person. say ();
The above Code demonstrates the basic method of object encapsulation in Javascript.
2. functions are objects
Objects have data attributes, methods, and prototype objects. The prototype of the Function is Function. prototype. Continue with the previous example:
Worker. salary = '6k ';
Document. write ("My salary is" + worker. salary );
Document. write ("My type is" + worker. typename );
Function. prototype. typename = 'func'; // set the typename attribute of all functions to func.
Document. write ("My type is" + worker. typename );
Document. write ("My type is" + choice. typename );
Function. prototype. fsay = function () {// Add the fsay method to all functions
Document. write ('Hey, I am a function, the first class object in javascript ');
}
Worker. fsay ();
Choice. fsay ();
Worker. mycareer = function (career) {// Add method only for the worker function
Document. write ('I am worker' + career );
}
Worker. mycareer ('a programmer ');
Choice. mycareer ('a choice '); // Error: Has no method 'mycareer'
The biggest advantage of prototype-based Inheritance Mechanism is dynamic and flexible. You can dynamically add any attributes and methods at runtime. Of course, excessive abuse will lead to chaos.
3. Closure
The function can be nested in another function, and the inner function can access the private variables of the outer function to expand its scope.
Var secretMan = function (){
Var secret = 'very very important secret. Poison case happened in tsinghua 19 years ago ';
Var getSecret = function (){
Return secret;
}
Return getSecret;
}
Document. write ("The secret:" + secret); // Error: ReferenceError: secret is not defined
Var revealTruth = secretMan ();
Document. write ('now is the time to reveal it out: '+ revealTruth ());
// Page print: Now is the time to reveal it out: very important secret. Poison case happened in tsinghua 19 years ago
Iv. Call mode and this
There are four call modes for a function: using the variable reference, through the object method, through the constructor, through the apply function.
1. variable reference: stores function objects in variables and calls them through variable reference. This is bound to a global object;
2. Object method: the function is called as an object method. this is dynamically bound to the object currently calling the function. The binding takes place during the call;
3. constructor: a function is used to create and initialize a new object. this is bound to the newly created object;
4. apply: input the apply function as a parameter. this is bound to the specified object.
First case:
Var outer = function (){
Document. write ('outer this: '+ this); // [object Window]
Var inner = function (){
Document. write ('inner this: '+ this); // [object Window]
};
Inner ();
}
Outer ();
Case 2:
Var person = {
Name: 'shuqin ',
Sayme: function (){
Document. write ("Object this:" + this. name); // Shuqin
(Function (){
Document. write ('inner this: '+ this); // [object Window], this is switched!
})();
}
}
Person. sayme ();
Case 3:
Var Man = function (name, power ){
This. name = name; // this is bound to the new object to be created.
This. sex = 'man ';
This. power = power;
This. ability = function (){
Document. write ('name: '+ this. Name + 'sex:' + this. Sex + 'power: '+ this. Power );
If (this. power <80 ){
Document. write ('Oh, no, you power is little, you must strengthen it! ');
}
}
}
Var me = new Man ('shuqin', 60 );
Me. ability ();
Case 4:
Var generalsum = function (callback, args ){
Document. write ("generalsum this:" + this );
Var result = 0;
Var caller;
If (typeof this = 'function '){
Caller = this;
}
Else {
Caller = callback;
}
Document. write (typeof caller) + ''+ args. join (''))
For (I = 0; I <args. length; I ++ ){
Result + = caller (args [I]);
Document. write (result );
}
Return result;
};
Var plainsumdef = function (num) {return num ;}
Generalsum (plainsumdef, [1, 2, 3, 4, 5]); // this: [object Window]
Var plainsum = generalsum. apply (plainsumdef, [null, [1, 2, 4, 5]); // this: function (num) {return num ;}
In this case, this is bound to the specified object.
Summary
This article discusses Javascript Functions, and the examples tend to illustrate their basic features. In practice, you also need to use it in depth to develop a variety of advanced skills. Understanding it will become a key to understanding javascript.