JavaScript functions

Good_ fast 2021-01-21 04:49:59
javascript functions


1、 Function description

1.1 Function is first class (first-class) object

  • Because they can have properties and methods like any other object .
  • The difference between them and other objects is that functions can be called .
  • Every function is actually a Function object

1.2 Return value

  • Default return undefined
  • Use return Statement to specify a value to return ( Use new Keyword to call a constructor )

1.3 Function parameter

  • When you call a function , The value passed to a function is called the function's argument ( Value passed ),
  • The function parameter corresponding to the position is called formal parameter .
  • If the argument is one that contains the original value ( Numbers , character string , Boolean value ) The variable of , Even if the function changes the value of the corresponding parameter inside , After the return , The value of the argument variable does not change .
  • If the argument is an object reference , Then the corresponding shape participant and the actual parameter point to the same object . If the function changes the value of the corresponding parameter inside , After the return , The value of the object that the argument points to also changes .

1.4 this Point to

  • At function execution time ,this The keyword does not point to the running function itself , It points to the object that called the function
  • If you want to get a reference to the function itself inside the function , You can only use function names or arguments.callee attribute ( Not available in strict mode ), If the function is anonymous , You can only use the latter .

2、 Function definition

2.1 Function declaration

2.1.1 usage

function name([ Parameters , Parameters , ... Parameters ) { statements }
 Copy code 
function myFunc(theObject) {
theObject.make = "Toyota";
}
var mycar = {make: "Honda", model: "Accord", year: 1998};
var x, y;
x = mycar.make; // x The value obtained is "Honda"
myFunc(mycar);
y = mycar.make; // y The value obtained is "Toyota"
// (make Property changed by function )
 Copy code 

2.1.2 Function declaration promotion

  • JavaScript The function declaration in is promoted to the function definition , You can use the function before it is declared .
  • The function declaration also creates a variable with the same name as the function . therefore , Functions defined by function declaration can be accessed by function name in their defined scope
hoisted(); // "foo"
function hoisted() {
console.log("foo");
}
/* equal to*/
var hoisted;
hoisted = function() {
console.log("foo");
}
hoisted();
// "foo" 
 Copy code 

2.2 Function expression

2.2.1 usage

let Variable name = function The name of the function ( Parameters , Parameters , ... Parameters ) {
statements
};
 Copy code 
  • Function names can be omitted , The function in this case is anonymous (anonymous)
  • The function name is just a local variable in the function body .
const square = function(number) { return number * number; };
var x = square(4); // x gets the value 16
const factorial = function fac(n) {return n<2 ? 1 : n*fac(n-1)};
console.log(factorial(3));
 Copy code 

2.2.2 No promotion

 notHoisted(); // TypeError: notHoisted is not a function
var notHoisted = function() {
console.log('bar');
};
 Copy code 

2.3 Function builder declaration (function* Statement )

Define a generator function (generator function), It returns a Generator object .

function* Function name ( Parameters , Parameters , ... Parameters ) { statements }
 Copy code 
function* generator(i) {
yield i;
yield i + 10;
}
const gen = generator(10);
console.log(gen.next().value);
// expected output: 10
console.log(gen.next().value);
// expected output: 20
 Copy code 
  • Generator functions can pause while executing , After that, it can continue from the pause .
  • Calling a generator function does not immediately execute the statements in it , Instead, it returns a iterator ( iterator ) object .
  • When this iterator's next() The method was first ( follow-up ) Invocation time , The statements in it are executed to the first ( follow-up ) appear yield Up to ,yield Followed by the value to be returned by the iterator .
  • Or if you use yield*( There's an extra asterisk ), It means to transfer the execution right to another generator function ( The current generator is paused ).
  • next() Method returns an object , This object contains two properties :value and done,
  • value Property indicates this time yield Return value of expression ,
  • done Property is boolean type , Indicates whether the generator will have any follow-up information yield sentence , That is, whether the generator function has been executed and returned .

2.4 Function builder expression (function* expression )

  • function* Expression and function* The statement is similar , And it has almost the same syntax .
  • function* Expression and function* The main difference between declarations is the function name ,
  • That is, when you create an anonymous function ,function* Expressions can omit function names
var x = function*(y) {
yield y * y;
};
 Copy code 

2.5 Arrow function expression (=>)

(param1, param2, …, paramN) => { statements }
 Copy code 
  • Shorter functions
  • No binding this

2.5.1 Shorter functions

var elements = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];
elements.map(function(element) {
return element.length;
}); // Returns an array of :[8, 6, 7, 9]
// The above ordinary function can be rewritten as the following arrow function 
elements.map((element) => {
return element.length;
}); // [8, 6, 7, 9]
// When the arrow function has only one parameter , You can omit parentheses for parameters 
elements.map(element => {
return element.length;
}); // [8, 6, 7, 9]
// When there is only one body of arrow function `return` When the sentence is , It can be omitted `return` Curly braces for keywords and method bodies 
elements.map(element => element.length); // [8, 6, 7, 9]
// In this case , Because we just need `length` attribute , So you can use parameters to deconstruct 
// Note that the string `"length"` Is the name of the property we want to get , and `lengthFooBArX` It's just a variable name ,
// It can be replaced with any legal variable name 
elements.map(({ "length": lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9]
 Copy code 

2.5.2 No binding this

function Person() {
// Person() Constructor definition `this` As an example of itself .
this.age = 0;
setInterval(function growUp() {
// In the non strict mode , growUp() Function definition `this` As a global object ,
// And in Person() Defined in the constructor `this` Is not the same .
this.age++;
}, 1000);
}
var p = new Person();
 Copy code 
<!-- By way of this Values are assigned to closed variables , Can solve this problem -->
function Person() {
var that = this;
that.age = 0;
setInterval(function growUp() {
// Callbacks refer to `that` Variable , Its value is the expected object .
that.age++;
}, 1000);
}
 Copy code 
<!-- Arrow functions do not create their own this, It will only inherit from the upper level of its scope chain this-->
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // |this| Point to... Correctly p example 
}, 1000);
}
var p = new Person();
 Copy code 

2.6 Function Constructor expression ( Not recommended

// The result is true Prove that all functions are one Function object 
(function(){}).constructor === Function //true
 Copy code 

2.6.1 describe

  • Use Function Constructor generated Function Object is resolved at function creation time .
  • This is more inefficient than using function declarations or function expressions and calling them in your code. ,
  • Because functions created with the latter are parsed with other code .
  • Call as a function Function Constructor for ( Instead of using new keyword ) It's the same as calling with a constructor .
<!-- It can be executed normally -->
const sum = new Function("a", "b", "return a + b");
console.log(sum(2, 6));
<!-- It can be executed normally -->
const sum2 = Function.prototype.constructor( "a", "b", "return a + b" );
console.log(sum2(2, 6));
 Copy code 
<!-- usage -->
new Function ( Parameters , Parameters , ... Parameters , functionBody character string )
// for example
const sum = new Function('a', 'b', 'return a + b');
console.log(sum(2, 6));
// expected output: 8
 Copy code 

2.6.2 Instance attributes

  • Function.caller Gets the specific object of the calling function .( There are compatibility issues )
  • Function.length Get the number of received parameters of the function .
  • Function.name Gets the name of the function .

2.6.3 Example method

  • Function.prototype.apply() The method of applying another object in the context of one object ; Parameters can be passed in as arrays .
  • Function.prototype.bind()
    • bind() Method creates a new function , It's called a binding function .
    • When this binding function is called , The binding function will pass in... When it is created bind() The first parameter of the method is this,
    • Pass in bind() The second and later parameters of the method, plus the parameters of the binding function runtime itself, call the original function in order as the parameters of the original function .
  • Function.prototype.call() The method of applying another object in the context of one object ; Parameters can be passed in as a list .
  • Function.prototype.toString() Get the implementation source string of the function . covers Object.prototype.toString Method .

2.6.4 And function declaration 、 Function expression difference

  • Like function expressions, there is no function declaration promotion . Cannot be invoked before declaration.
  • The current environment closure cannot be created , Can only be created in a global environment
  • You can only access global variables and your own local variables
 const x = 10;
function createFunction1() {
const x = 20;
return new Function("return x;"); // there x Points to the x
}
function createFunction2() {
const x = 20;
function f() {
return x; // there x Points to the x
}
return f;
}
const f1 = createFunction1();
console.log(f1()); // 10
const f2 = createFunction2();
console.log(f2()); // 20
 Copy code 

2.6.5 Reasons to avoid use

  • Every time the constructor is called , Pass to Function The function body string of the constructor must be parsed once .

  • Although function expressions create a closure every time , But the body of the function is not parsed repeatedly , So the function expression is still faster than "new Function(...)"

  • Through analysis Function In the function generated by the constructor string , Embedded function expressions and function declarations are not parsed repeatedly .

2.7 Constructor of generator function ( Not recommended

  • GeneratorFunction The constructor generates a new generator function object .
  • stay JavaScript in , Generator functions are actually GeneratorFunction Instance object of .
  • GeneratorFunction Not a global object . It can be obtained through the following code .
Object.getPrototypeOf(function*(){}).constructor
 Copy code 

2.7.1 grammar

new GeneratorFunction ([arg1[, arg2[, ...argN]],] functionBody character string )
 Copy code 
var GeneratorFunction = Object.getPrototypeOf(function*(){}).constructor
var g = new GeneratorFunction("a", "yield a * 2");
var iterator = g(10);
console.log(iterator.next().value); // 20
 Copy code 

2.7.2 Reasons to avoid use

  • When creating a function , Will use GeneratorFunction Constructor to create the generator function object for parsing .
  • This is better than using function* expression Less efficient declaration generator functions ,
  • Use GeneratorFunction Constructor creates a generator function that does not create a closure for its creation context ; They are always created globally .
  • When you run them , They can only access their own local and global variables , Not from GeneratorFunction Variable in the scope of the constructor call .

3、 Function scope

  • Variables defined within a function cannot be accessed anywhere outside the function , Because variables are only defined within the domain of the function .
  • A function can access any variables and functions within the scope of its definition . for example , Functions defined in the global domain can access all variables defined in the global domain .
  • A function defined in another function can also access all variables defined in its parent function and any other variables that the parent function has access to .
// The following variables are defined in the global scope (global scope) in 
var num1 = 20,
num2 = 3,
name = "Chamahk";
// This function is defined in the global scope 
function multiply() {
return num1 * num2;
}
multiply(); // return 60
// Examples of nested functions 
function getScore() {
var num1 = 2,
num2 = 3;
function add() {
return name + " scored " + (num1 + num2);
}
return add();
}
getScore(); // return "Chamahk scored 5"
 Copy code 

4、 Closure

  • JavaScript Allow function nesting ,
  • Internal functions can access all variables and functions defined in external functions , And all variables and functions that external functions can access .
  • External functions cannot access variables and functions defined in internal functions . This provides some security for variables of internal functions .
  • Because internal functions can access the scope of external functions , Therefore, when the life cycle of internal function is longer than that of external function , The lifetime of variables and functions defined in external functions will be longer than that of internal functions .
  • When an internal function is accessed in some way by any external function scope , A closure is produced .
var pet = function(name) { // The external function defines a variable "name"
var getName = function() {
// Internal functions can be accessed Definition of external function "name"
return name;
}
// Return this inner function , This exposes it to the scope of the external function 
return getName;
};
myPet = pet("Vivie");
myPet();
 Copy code 

4.1 name conflict

  • When two parameters or variables in the same closure scope have the same name , There will be naming conflicts .
  • Closer scopes have higher priority , So the nearest priority is the highest , The farthest has the lowest priority . This is the scope chain .
  • The first element of the chain is the innermost scope , The last element is the outermost scope .
function outside() {
var x = 5;
function inside(x) {
return x * 2;
}
return inside;
}
outside()(10); // returns 20 instead of 10
 Copy code 

5.arguments object

  • arguments Is an array of class objects corresponding to the parameters passed to the function
  • arguments Variables are just ” Class array object “, It's not an array .
  • Called a class array object, it has an index number and length attribute .
  • For all that , It doesn't have all of them Array Object operation method .
  • arguments Object is all ( The arrow ) Local variables that are available in all functions .
function func1(a, b, c) {
console.log(arguments[0]);
// expected output: 1
console.log(arguments[1]);
// expected output: 2
console.log(arguments[2]);
// expected output: 3
}
func1(1, 2, 3);
 Copy code 

5.1 attribute

  • arguments.callee : The currently executing function .
  • arguments.caller : Call the function that currently executes the function .
  • arguments.length : The number of arguments passed to the function .

6. Function parameter

from ECMAScript 6 Start , There are two new types of parameters : Default parameters , The remaining parameters

6.1 Default parameters

stay JavaScript in , The default value of the function parameter is undefined. in the past , The general strategy for setting default parameters is to test whether the parameter value is in the body of the function undefined, If so, give this parameter a default value .

function multiply(a, b) {
b = (typeof b !== 'undefined') ? b : 1;
return a*b;
}
multiply(5); // 5
 Copy code 
<!-- Using default parameters , Checking the body of a function is no longer necessary -->
function multiply(a, b = 1) {
return a*b;
}
multiply(5); // 5
 Copy code 

6.2 The remaining parameters

The remaining parameter syntax allows an indefinite number of parameters to be represented as an array .

function multiply(multiplier, ...theArgs) {
return theArgs.map(x => multiplier * x);
}
var arr = multiply(2, 1, 2, 3);
console.log(arr); // [2, 4, 6]
 Copy code 

Reference link

版权声明
本文为[Good_ fast]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210121044620110o.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云