Home >Web Front-end >JS Tutorial >Detailed explanation of JavaScript functions
In many traditional languages (C/C++/Java/C#, etc.), functions exist as second-class citizens. You can only declare a function using language keywords and then call it. If you need to When a function is passed as a parameter to another function, or assigned to a local variable, or used as a return value, special methods such as function pointers and delegates are required.
In the JavaScript world, functions are first-class citizens. They not only have all the ways to use traditional functions (declaration and calling), but also can be assigned and passed like simple values. Parameters and returns, such a function is also called a first-class function. Not only that, the function in JavaScript also acts as the constructor of the class and is an instance of the Function class. Such multiple identities make JavaScript functions very important.
1. Entry-level JavaScript functions
Like other languages, JavaScript functions follow the principle of declaration first and then use. Function names can only contain letters, numbers, underscores or $, and cannot start with a number. There are two common ways of declaring functions:
The code is as follows:
// 直接声明函数myfunc function myfunc(/* arguments */) { } // 把匿名函数赋值给本地变量myfunc var myfunc = function(/* arguments */) { }
Note that there are subtle differences in the above two ways of declaring functions: the first way is a named one when declaring Functions, whether they are declared before the call, after the call, or even in a position that will not be executed (such as after the return statement or in a branch that will never be true), are accessible in the entire scope; the second way is By assigning an anonymous function to a variable, strictly speaking, this is not a function declaration but a function expression. This function cannot be accessed by any code before the assignment, that is to say This assignment must be completed before calling, otherwise an error will occur when calling: "TypeError: undefined is not a function". For example:
The code is as follows:
myfunc1(); // 能够正常调用,因为myfunc1采用直接声明的方式 function myfunc1() { } myfunc2(); // 出错 TypeError: undefined is not a function var myfunc2 = function() { };
The basic calling method of the function is the same as that in traditional languages, using a pair of brackets: myfunc(). JavaScript functions also support direct or indirect recursive calls. For example, the classic Fibonacci function can be implemented in JavaScript like this:
The code is as follows:
function fib(n) { if (n == 1 || n == 2) { return 1; } else { return fib(n - 2) + fib(n - 1); } }
Functions in JavaScript can handle variable-length parameters. Inside the function, there is a local variable named arguments, which is an array-like object that contains all the parameters passed in when calling, including length The attribute represents the number of parameters. For example:
The code is as follows:
function test() { alert(arguments.length); } test(1); // 1 test(1, 'a'); // 2 test(true, [], {}); // 3 利用arguments可以实现类似C语言printf的功能,也可以用来实现方法的多态。
2. Advanced JavaScript functions
##2.1 Anonymous Functions and nested functions
In JavaScript, you can declare a function without a name, called an anonymous function (Anonymouse Function). At the same time, JavaScript also allows functions to be declared inside functions, called nested functions. The scope of a nested function is the entire parent function.
In the previous part of function declaration, we saw a use of anonymous functions and nested functions. Since anonymous functions have no names, they will not introduce new variables to pollute the context, and will bring new variable effects. domain, so anonymous functions are often used to prevent global environment pollution.
There is a special global environment (global object) in JavaScript runtime. This object stores global functions and variables. In actual development, several third-party libraries or multiple js files are often used. If not Be careful to introduce repeated variable or function declarations in the global object, which will cause confusion in code execution. For example, two js files are introduced one after another, and each defines its own function log for internal use. The second introduced function will overwrite the first definition and will not throw any errors. Calling the log function in subsequent executions may cause problems. causing errors. At this time, using an anonymous function to wrap the logic in the entire js can avoid this error. This method has been used by most open source js libraries.
The code is as follows:
(function() { // 匿名函数 function log(msg) { console.log(msg); } // 其他代码 }()); // 立即执行The above code is a simple example. The scope of the log function is limited to this anonymous function, and the anonymous function Because it is enclosed by an outer pair of parentheses (), it forms a function expression, and the value of the expression is a function. The next pair of parentheses indicates that the function will be executed immediately, allowing the original code to be executed normally. However, functions declared in this way, variables declared via var, etc. are internal and cannot be accessed by any code other than anonymous functions. If you need to expose some functions as interfaces, there are several methods as follows:
The code is as follows:
var mylib = (function(global) { function log(msg) { console.log(msg); } log1 = log; // 法一:利用没有var的变量声明的默认行为,在log1成为全局变量(不推荐) global.log2 = log; // 法二:直接在全局对象上添加log2属性,赋值为log函数(推荐) return { // 法三:通过匿名函数返回值得到一系列接口函数集合对象,赋值给全局变量mylib(推荐) log: log }; }(window));
2.2 High-order functions (High -order Function)
代码如下:
function negative(n) { return -n; // 取n的相反值 } function square(n) { return n*n; // n的平方 } function process(nums, callback) { var result = []; for(var i = 0, length = nums.length; i < length; i++) { result[i] = callback(nums[i]); // 对数组nums中的所有元素传递给callback进行处理,将返回值作为结果保存 } return result; } var nums = [-3, -2, -1, 0, 1, 2, 3, 4]; var n_neg = process(nums, negative); // n_neg = [3, 2, 1, 0, -1, -2, -3, -4]; var n_square = process(nums, square); // n_square = [9, 4, 1, 0, 1, 4, 9, 16];
以上代码展示了把函数作为参数传入另一个函数process调用的示例,在process函数的实现中,把callback作为一个黑盒子看待,负责把参数传给它,然后获取返回值,在调用之前并不清楚callback的具体实现。只有当执行到20行和22行时,callback才被分别代表negative或square,分别对每个元素进行取相反值或平方值的操作。
代码如下:
function generator() { var i = 0; return function() { return i++; }; } var gen1 = generator(); // 得到一个自然数生成器 var gen2 = generator(); // 得到另一个自然数生成器 var r1 = gen1(); // r1 = 0 var r2 = gen1(); // r2 = 1 var r3 = gen2(); // r3 = 0 var r4 = gen2(); // r4 = 1
上面的代码展示了把函数作为返回值的示例,generator是一个自然数生成器函数,返回值是一个自然数生成函数。每次调用generator时都会把一个匿名函数作为结果返回,这个匿名函数在被实际调用时依次返回每个自然数。在generator里的变量i在每次调用这个匿名函数时都会自增1,这其实就是一个闭包。下面我们来介绍一下闭包.
2.3 闭包(Closure)
闭包(Closure)并不是一个新鲜的概念,很多函数式语言中都使用了闭包。在JavaScript中,当你在内嵌函数中使用外部函数作用域内的变量时,就是使用了闭包。用一个常用的类比来解释闭包和类(Class)的关系:类是带函数的数据,闭包是带数据的函数。
闭包中使用的变量有一个特性,就是它们不在父函数返回时释放,而是随着闭包生命周期的结束而结束。比如像上一节中generator的例子,gen1和gen2分别使用了相互独立的变量i(在gen1的i自增1的时候,gen2的i并不受影响,反之亦然),只要gen1或gen2这两个变量没有被JavaScript引擎垃圾回收,他们各自的变量i就不会被释放。在JavaScript编程中,不知不觉就会使用到闭包,闭包的这个特性在带来易用的同时,也容易带来类似内存泄露的问题。例如:
代码如下:
var elem = document.getElementById('test'); elem.addEventListener('click', function() { alert('You clicked ' + elem.tagName); });
这段代码的作用是点击一个结点时显示它的标签名称,它把一个匿名函数注册为一个DOM结点的click事件处理函数,函数内引用了一个DOM对象elem,就形成了闭包。这就会产生一个循环引用,即:DOM->闭包->DOM->闭包...DOM对象在闭包释放之前不会被释放;而闭包作为DOM对象的事件处理函数存在,所以在DOM对象释放前闭包不会释放,即使DOM对象在DOM tree中删除,由于这个循环引用的存在,DOM对象和闭包都不会被释放。可以用下面的方法可以避免这种内存泄露:
代码如下:
var elem = document.getElementById('test'); elem.addEventListener('click', function() { alert('You clicked ' + this.tagName); // 不再直接引用elem变量 });
上面这段代码中用this代替elem(在DOM事件处理函数中this指针指向DOM元素本身),让JS运行时不再认为这个函数中使用了父类的变量,因此不再形成闭包。
闭包还会带来很多类似的内存泄露问题,只有在写代码的时候着重注意一下闭包,尽量避免此类的问题产生。
2.4 类构造函数
JavaScript的函数同时作为类的构造函数,因此只要声明一个函数就可以使用new关键字创建类的实例。
代码如下:
function Person(name) { this.name = name; this.toString = function() { return 'Hello, ' + this.name + '!'; }; } var p = new Person('Ghostheaven');
alert(p); // Hello, Ghostheaven! 在以上实例中Person函数作为类的构造函数使用,此时this指向新创建的实例对象,可以为实例增加属性和方法,关于详细的面向对象的JavaScript编程可以参考这篇文章。这里我想要说的是,JavaScript函数作为类构造函数使用时的返回值问题。
代码如下:
function MyClass(name) { this.name = name; return name; // 构造函数的返回值? } var obj1 = new MyClass('foo'); var obj2 = MyClass('foo'); var obj3 = new MyClass({}); var obj4 = MyClass({});
上面的构造函数比较特别,有返回语句,那么obj1~obj4分别指向什么对象呢?实际结果是这样的:
复制代码 代码如下:
obj1 = MyClass对象 obj2 = 'foo' obj3 = {} obj4 = {}
具体原因这篇文章有解释,本文不再赘述,由于带返回值的构造函数会产生奇怪的结果,因此不要在构造函数中调用有返回值的返回语句(空return可以)。
三、JavaScript函数妖怪级
欢迎来到妖怪级函数授课区,在这里会交给你如何淡定自如地面对老怪。。。
3.1 Function类
在JavaScript运行时中有一个内建的类叫做Function,用function关键字声明一个函数其实是创建Function类对象的一种简写形式,所有的函数都拥有Function类所有的方法,例如call、apply、bind等等,可以通过instanceof关键字来验证这个说法。
既然Function是一个类,那么它的构造函数就是Function(它本身也是Function类的对象),应该可以通过new关键字来生成一个函数对象。第一个妖怪来了,那就是如何用Function类构造一个函数。Function的语法如下:
代码如下:
new Function ([arg1[, arg2[, ... argN]],] functionBody)
其中arg1, arg2, ... argN是字符串,代表参数名称,functionBody也是字符串,表示函数体,前面的参数名称是可多可少的,Function的构造函数会把最后一个参数当做函数体,前面的都当做参数处理。
代码如下:
var func1 = new Function('name', 'return "Hello, " + name + "!";'); func1('Ghostheaven'); // Hello, Ghostheaven!
以上方法就通过Function构造了一个函数,这个函数跟其他用function关键字声明的函数一模一样。
看到这儿,很多人可能会问为什么需要这样一个妖怪呢?“存在的即是合理的”,Function类有它独特的用途,你可以利用它动态地生成各种函数逻辑,或者代替eval函数的功能,而且能保持当前环境不会被污染*。
3.2 自更新函数(Self-update Function)
在很多语言中,函数一旦声明过就不能再次声明同名函数,否则会产生语法错误,而在JavaScript中的函数不仅可以重复声明,而且还可以自己更新自己。自己吃自己的妖怪来了!
代码如下:
function selfUpdate() { window.selfUpdate = function() { alert('second run!'); }; alert('first run!'); } selfUpdate(); // first run! selfUpdate(); // second run! 这种函数可以用于只运行一次的逻辑,在第一次运行之后就整个替换成一段新的逻辑。
小结
JavaScript的函数灰常强大,在漂亮地解决很多问题的同时,也带来很多负面问题。妖怪级别的函数使用方法通常是一些鲜为人知的用法,除非特别必要不要轻易使用,否则会造成代码阅读困难,影响团队开发效率。
* 在新的ECMAScript中引入了严格模式,在严格模式下eval函数受到了很大的限制,也能够保证环境不被污染
The above is the detailed content of Detailed explanation of JavaScript functions. For more information, please follow other related articles on the PHP Chinese website!