Home > Web Front-end > JS Tutorial > Detailed explanation of JavaScript functions_javascript skills

Detailed explanation of JavaScript functions_javascript skills

WBOY
Release: 2016-05-16 16:12:34
Original
1253 people have browsed it

1. Function definition

Functions contain a set of statements, which are the basic module units of JavaScript and are used for code reuse, information hiding and combined calls. Functions are used to specify the behavior of objects

2. Four calling modes of functions and initialization of this

The first: method calling mode
The following example proves that when called through the method calling mode, this is bound to the object that owns the method. Such as:

Copy code The code is as follows:

var person = {
name: "defaultName",
setName : function(name){
This.name = name;
}
};
person.setName("zhangsan");
alert(person.name);

Second type: Function calling mode
The following example proves that when called through the function calling mode, this is bound to the global object. Such as:

Copy code The code is as follows:

var test = add(value1, value2);
var name = "defaultName";
var person = {
name: "zhangsan", // name
defined in person GetName : function(){
// This method can change the this of the test function to the this object of person
        var that = this; // Solution
                // name
defined in getName         var name = "lisi";
         var test = function(){
//Access the objects in person through that
// this points to the Global object
                            // this.name = defaultName
                       // that.name = zhangsan
alert([this.name, that.name]);
        };
          test(); // Function calling mode
}
}
person.getName();

Third type: Constructor calling mode

Copy code The code is as follows:

//Define a Person constructor, which must be called with new
var Person = function(name){
This.name = name;
}
// Add a method to Person
Person.prototype.getName = function(){
Return this.name;
};
//Construct a Person object
var person = new Person("zhangsan");
alert(person.getName()); // Call getName to get the value of the name attribute in the person object

Fourth: Apply calling mode

Copy code The code is as follows:


3. The difference between apply and call

Copy code The code is as follows:

// Define an object, including an add method, returning the sum of a and b
var Person = {
'add' : function(a, b){
          return a b;
}
};
// Display the sum of a and b
function showInfo(a, b){
alert(this.add(a, b));
}
// Change the this point of the showInfo method through the apply method
//showInfo(1, 3); // The object does not support secondary objects
showInfo.apply(Person, [1, 3]);
showInfo.call(Person, 1, 3);
// As can be seen from the above, the difference between apply and call is that apply accepts an array as a parameter of the called function,
// And call expands all parameters of the called function in comma-separated form

4. Function parameters (arguments)
arguments is not an array, but similar to an array. In addition to having the length property, arguments does not have all the properties and methods of the array. Use arguments to implement an accumulative function.

Copy code The code is as follows:

function sum(){
var total = 0;
for(var i=0; i          total = arguments[i];
}
Return total;
}
alert("sum: " sum(1, 3, 2, 4));

5. Function return value (return)
When a function is called, it is usually executed from { to } of the function. If you want to end the execution of the function early, you can use the return statement. At this time, all statements following the return statement will never be executed. Such as:

Copy code The code is as follows:

function test(){
alert("first");
Return;
alert("second"); // This statement will never be executed
}
test();
// A function always returns a value. If the return value is not used, undefined is returned by default. Such as:
function test(){
alert("first");
}
alert(test()); // Output: undefined
// If the function is called using new method and the return value is not an object, return this (new object). Such as:
function test(){
alert("first");
}
var t = new test();
alert(typeof t); // Output: 'object'
alert(t instanceof test); // Output: true

6. Exception

Anomalies are abnormal accidents (maybe intentional) that interfere with the normal flow of the program. When such an incident is detected, an exception should be thrown. Such as:

Copy code The code is as follows:

function add(a, b){ // Define an addition function
// If the passed parameter is not of numeric type, an exception message is thrown
If(typeof a != 'number' || typeof b != 'number'){
throw {
             'name' : "typeError", // The attribute is customized and the name can be anything
              'message': "The add method must use numbers as parameters"
        };
}
Return a b;
}
(function(){
//Catch possible exceptions generated by the add method
Try{
         add(10, "");
} catch(e){
​​​​ //A try statement has only one catch statement. If multiple exceptions are to be handled, they are distinguished by the name attribute of the exception
​​​​ // Determine the type of exception
If(e.name === "typeError"){
alert(e.message);
}
}
})();

7. Add methods to types
JavaScript allows adding methods to basic types. Such as: boolean, string, Number
Example: Add a method function to Function, which adds other custom functions to Function (avoid using prototype), then use the method function to add an add function to Function, and finally test that the add function does exist in Function. This method adds the func function to Function and names it with name. Then, return the Function object

Copy code The code is as follows:

Function.prototype.method = function(name, func){
// Avoid overwriting existing methods
If(!this.prototype[name]){
This.prototype[name] = func;
}
Return this;
};
//Add an addition function to Function through the Function.method method. The name of the function is "add"
Function.method("add", function(a, b){
If(typeof a != 'number' || typeof b != 'number'){
throw {
            'name' : "typeError",
            'message' : "The add method must pass in a number"
        };
}
Return a b;
});
// Call the add method of Function to see if it exists
(function(){
Try{
alert(Function.add(1, 3)); // Output: 4
} catch(e){
If(e.name === 'typeError'){
alert(e.message);
}
}
})();
//Remove whitespace at both ends of the string
String.method("trim", function(){
Return this.replace(/^s |s $/g, '');
});
alert('|' " hello world ".trim() '|'); // Output: '|hello world|'
//Add number rounding function
Number.method("integer", function(){
// You can call functions in this way, such as: Math.random() == Math['random']() == Math["random"]()
Return Math[this < 0 ? 'ceil' : 'floor'](this);
});
alert((-10 / 3).integer()); // Output: -3

8. Recursive call (arguments.callee)
Recursive calling means calling yourself. Calls are divided into: direct calls and indirect calls. The following shows the use of recursive calls to calculate the Fibonacci sequence of the specified value.

Copy code The code is as follows:

// Find the factorial of i
function factorial(i){
If(i < 2){
Return 1;
}
Return i*factorial(i-1); // Recursive call
}
alert(factorial(5)); // Find the factorial of 5
// Is there a problem with the above method? As follows:
var factorial = function(i){
If(i < 2){
Return 1;
}
Return i*factorial(i-1); // Can factorial still be called? Can't
}
var test = factorial;
factorial = null;
alert(test(2));
// Solution:
var factorial = function(i){
If(i < 2){
Return 1;
}
Return i*arguments.callee(i-1); // arguments.callee returns the Function object being executed, which is the body of the specified Function object
}
var test = factorial;
factorial = null;
alert(test(5));

9. Scope

Copy code The code is as follows:

// In a program, scope controls the visibility and life cycle of variables.
var name = "default"; // Global scope
function getName(){
var name = "getName"; // getName scope
for(var i=0; i<2; i ){
          var inName = "inName";
}
alert(i "," inName); // 2, inName Note: There is no block-level scope in js, and variables declared in if, for, while are placed in the scope of the block
Return name;
}
alert(getName()); // getName Note: js has function scope, so variables defined inside the function are not visible outside
alert(name); // default

Note: In many modern languages, it is recommended to delay declaration of variables as much as possible. Such as: java, but in js, this is not recommended because js does not support block-level scope. It is recommended to declare all variables used at the beginning of the function.

10. Closure
The context in which a function has access to the environment when it was created is called a closure. The benefit of scope is that the inner function can access all variables of the outer function (except this and arguments).

Copy code The code is as follows:

var myObject = {
value : 0,
increment : function(inc){
This.value = typeof inc === 'number' ? inc : 1;
},
GetValue : function(){
         return this.value;
}
};
myObject.increment(10);
alert(myObject.value);
alert(myObject.getValue());
// The above defines a myObject object using literal constants. But the value variable can be accessed by external objects
var myObject = function(){
var value = 0;
Return {
increment: function(inc){
value = typeof inc === 'number' ? inc : 1;
},
         getValue: function(){
             return value;
}
};
}();
myObject.increment(10);
alert(myObject.value); // Cannot be accessed by external objects
alert(myObject.getValue()); // 10
// Gradient body background color (yellow to white)
var fade = function(node){
var level = 1;
var step = function(){
        var hex = level.toString(16);
           node.style.backgroundColor = '#FFFF' hex hex;
If(level < 15){
Level = 1;
                setTimeout(step, 500); // If level is less than 15, the internal function calls itself
}
};
setTimeout(step, 1); // Call internal function
};
fade(document.body);
// Here's a really bad example
Click me...
// Display 3
when clicked Click me...
// Display 3
when clicked Click me...
// Display 3
when clicked var add_the_handlers = function(nodes){
var i;
for(i = 0; i < nodes.length; i = 1) {
Nodes[i].onclick = function(e){ // Function construction: i
alert(i);
        };
}
};
var objs = document.getElementsByName("test");
add_the_handlers(objs);
//The reason for the above is that the event function of the a tag is bound to the variable i, which is not the i value when the function was constructed.
// The solution is as follows:
var add_the_handlers = function(nodes){
var i;
for(i = 0; i < nodes.length; i = 1) {
nodes[i].onclick = function(i){
              return function(e){
                       alert(i); // The i output is the i passed in by the constructor, not the i bound to the event processing.
            };
         }(i);
}
};
var objs = document.getElementsByName("test");
add_the_handlers(objs);

11. Callbacks

Copy code The code is as follows:

// data represents parameters, and call_function represents callback function
function sendRequest(data, call_function){
// setTimeout to simulate the time it takes for the client to request data to be transmitted from the server.
// Call the callback function after 3 seconds (there is a client that implements the callback function)
setTimeout(function(){
          call_function(data); // Call the callback function
}, 3000);
}
//Test sendRequest function
sendRequest("parameter", function(context){
alert("context=" context);
});

12. Module
A module is a function or object that provides an interface but hides state and implementation.
General form: a function that defines private variables and functions; uses closures to create privileged functions that can access private variables and functions; finally returns this privileged function, or saves them to a place where they can be accessed.

Copy code The code is as follows:

Function.prototype.method = function(name,func){
This.prototype[name] = func;
Return this;
};
String.method("deentityify",function(){
var entity = {
         quot: '"',
                                                                                                        gt : '>'
};
Return function(){
             return this.replace(/&([^&;] );/g, function(a, b){ // How to know the values ​​​​of a and b, understand regular expressions
          var r = entity[b];
                return typeof r === "string" ? r : a;
        });
};
}());
alert("<">".deentityify()); // Test: <">

Note: The module mode is usually used in combination with the singleton mode. The singleton mode of JavaScript is an object created using object literals. The attribute value of the object can be a numerical value or a function, and the attribute value does not change during the life cycle of the object. Changes will occur.

13. Cascade (chain operation) For some methods that do not return a value, we return this instead of undefined, then we can start cascading (chaining) to operate the object. As follows:

Copy code The code is as follows:

var $ = function(id){
    var obj = document.getElementById(id);
    obj.setColor = function(color){
        this.style.color = color;
        return this;
    };
    obj.setBgColor = function(color){
        this.style.backgroundColor = color;
        return this; // 返回this对象,启动级联
    };
    obj.setFontSize = function(size){
        this.style.fontSize = size;
        return this;
    };
    return obj;
};
$("test").setColor("red")
         .setFontSize("30px")
         .setBgColor("blue");
// 改进后的代码:
(function(id){
    var _$ = function(id){
        this.element = document.getElementById(id);
    };
    _$.prototype = {
        setColor : function(color){
            this.element.style.color = color;
            return this;
        },
        setBgColor : function(color){
            this.element.style.backgroundColor = color;
            return this;
        },
        setFontSize : function(size){
            this.element.style.fontSize = size;
            return this;
        }
    };
    
    // 添加到window原型链中
    window.$ = function(id){
        return new _$(id);
    };
})();
$("test").setColor("red")
         .setFontSize("30px")
         .setBgColor("blue");

14、套用
    所谓套用就是将函数与传递给它的参数相结合,产生一个新的函数。如:下面代码中定义一个add()函数,该函数能够返回一个新的函数,并把参数值传递给这个新函数,从而实现连加操作。

复制代码 代码如下:

// First way:
var add = function(a){
Return function(b){
          return a b;
}
};
alert(add(1)(2)); // 3
// The second way: use arguments to implement
var add = function(){
var arg = arguments;
Return function(){
      var sum = 0;
for(var i=0; i             sum = arg[i];
}
for(i=0; i              sum = arguments[i];
}
        return sum;
}
};
alert(add(1,2,3)(4,5,6)); // 21
// The third way: implement
through an application method (curry) var add = function(){
var sum = 0;
for(var i=0; i         sum = arguments[i];
}
Return sum;
};
//Add method to Function’s prototype chain
Function.prototype.method = function(name, func){
This.prototype[name] = func;
Return this;
};
//Apply method
Function.method('curry', function(){
// Through the slice method of the array Array, the arguments also have the concat method
var slice = Array.prototype.slice,
        args = slice.apply(arguments), that = this;
Return function(){
          return that.apply(null, args.concat(slice.apply(arguments)));
};
});
alert(add.curry(1,2)(3,4)); // 10

15. Memory
Functions can use objects to remember the results of previous operations, thereby avoiding unnecessary operations. This optimization is called memorization.

Copy code The code is as follows:

var fibonacci = function(){
var mome = [0,1]; // Store calculated data
var fib = function(n){
         var result = mome[n];
              // If there is no calculated data, calculate it directly. Then cache the calculation results
If(typeof result !== 'number'){
result = fib(n-1) fib(n-2);
              mome[n] = result;
}
        return result;
};
Return fib;
}();
for(var i=0; i<=10; i ){
​ document.writeln("// " i ": " fibonacci(i) "
");
}
//==========================
//Create a function with memory
//==========================
var memoizer = function(memo, fundamental){
var shell = function(n){
         var result = memo[n];
If(typeof result !== "number"){
result = fundamental(shell, n);
              memo[n] = result;
}
        return result;
};
Return shell;
};
//Complete the Fibonacci sequence through the memory function memoizer
var fibonacci = memoizer([0,1], function(shell, n){
Return shell(n-1) shell(n-2);
});
//Complete factorial through memory function memoizer
var factorial = memoizer([1,1], function(shell, n){
Return n * shell(n-1);
});
for(var i=0; i<=15; i ){
​ document.writeln("// " i ": " factorial(i) "
");
}

Have you understood it, friends? It is very practical. If there is anything missing, please ask the experts for guidance and we can make progress together

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template