Summary of learning JavaScript Ninja Secrets (Second Edition) (1) -- functions

Oh, ha ha 2020-11-09 16:56:02
summary learning javascript ninja secrets


Preface

 The summary of this article and the content of learning , Let's start with chapter three ; The whole book takes about a week to study , In fact, you can finish your study in your spare time .
Basic knowledge of , It needs continuous learning and supplement , If the knowledge you can't use , We'll forget ; Plus I'm not a computer major , So I've been trying to make up for it .

Ways of learning

 There is an old saying ,“ It's just saying it, not doing it ”; So it's boring .
So you still have to tap the code and practice it yourself , It's all very important .

I recommend this one WeChat reading

Because you can... In your spare time , Use your mobile phone to read , also Reading aloud The function of ; sometimes , We are always distracted when we read technical books . You can use it app The recitation function of "let you concentrate more .
image

Be sure to type the code !!!!

We must learn to sum up by ourselves ; It's also important . Better a good memory than a bad pen , That's why .

image

JavaScript The electronic version of Ninja Secret script II

yes epub Version of ;《JavaScript Ninja secrets Second Edition .epub》; Reading the electronic version is for the convenience of It's easier for me to operate examples on the computer , Copy it directly , Breaking point .
If you need , So here's the documentation .
image

link : https://pan.baidu.com/s/1L30_... password : n56j


Let's start our summary and overview today . My title also says , This is a Summary of key contents , yes Convenient for you to quickly remember and recall knowledge points , A better way is to read it systematically .

And then there's something about it , I will introduce the sentences of the article directly , Please take it easy .
I'll sort it out in the order of the catalog

The first 3 Chapter Novice's first function lesson : Definition and parameters

Anything an object can do , Functions can also do .

Functions are also objects , The only thing that's special is that it's callable (invokable), That is, the function is called to perform an action .

Callback function

function useless(ninjaCallback) {
return ninjaCallback();
}
This function may not work , But it reflects a function's ability , That is, the function is used as an argument to another function , The function is then called with arguments .

Storage function

var store = {
nextId: 1, //⇽--- Track the next function to be copied
cache: {}, //⇽--- Use an object as a cache , We can store functions in it
add: function(fn) {
if (!fn.id) {
fn.id = this.nextId++;
this.cache[fn.id] = fn;
return true;
}
} //⇽--- Only if the function is unique , Add the function to the cache
};
function ninja(){}
assert(store.add(ninja),
"Function was safely added.");
assert(!store.add(ninja),
"But it was only added once."); //⇽--- Test that the code above works as expected 
fn.id Will be , Come in fn Unique identification of ; If you pass in the same function , We're going to find this id Is there , It won't be added in .
It's equivalent to modifying this fn Function attribute , Added a unique identifier ID;
If it's not added fn, So there's no such thing ID Mark .
fn.id = this.nextId++;

Function definition

JavaScript Provides several ways to define functions , Can be divided into 5 class .

Function declaration

 function myFun(){ return 1;}
Each function is declared with Compulsory function start , then Then the mandatory function name , And parentheses and a column of optional parameter names separated by commas .
Function declaration must be Has a function name Because they're separate statements . The basic requirement of a function is that it should be able to be called , So it has to Having a way of being quoted , So the only way to do that is by its name .

image

Function expression

var myFun = function (){ return 1;}
JavaScript The function in is the first type of object , In addition, it means that they can pass through Literal creation , Sure Assign values to variables and properties , It can be used as an argument passed to another function or the return value of a function .
Be careful ️:
 Function declarations and function expressions are different from each other in code , One more ` The more important difference ` yes :
* Function declaration , Function names are mandatory ;
* Function expression , The function name is completely optional .
Immediate function

image
The comparison between the call of a standard function and the immediate call of a function expression

Be careful ️: Bracketed function expressions

Function expressions are wrapped in a pair of brackets . Why do you do this ?

The reason is purely grammatical .JavaScript The parser must be able to Distinguish between function declaration and function expression The difference between
If you remove the bag Brackets around function expressions , Make the immediate call a separate statement function() {}(3),JavaScript Start The parsing will end , Because the independent sentence is function start , Then the parser thinks it's dealing with a function declaration . Each function declaration must have a name ( However, there is no specific name here ), So that's where the program goes Will report a mistake . To avoid mistakes , Function expressions should be enclosed in brackets , by JavaScript The parser indicates that it is processing a function expression rather than a statement .
funciton(){33}

image

Will report an error directly , Because this function declaration is a form of error .

If you put brackets , Or the unary operator
image

Function expressions should be enclosed in brackets , by JavaScript The parser indicates that it is processing a function expression rather than a statement .
There is also a relatively simple alternative (function(){}(33)) Can achieve the same goal ( But it's a little strange , So it's not often used ). Put the definition and call of immediate function in brackets , It can also be JavaScript The parser indicates that it is processing function expressions .
image
Unlike using parentheses to distinguish function expressions from function declarations , Here we use the unary operator +、-、! and ~. This practice is also used to JavaScript The engine indicates that it is dealing with expressions , Instead of statements .

Arrow function

const myFun =()=>{ return 1;}
or
var greet = name => "Greetings " + name; //⇽--- Define the arrow function ”

image

Notice the new operator —— Fat arrow symbol =>( The equal sign is followed by a greater than sign ) Is the core of defining arrow functions .

Function constructors

new Function('a', 'b', 'return a + b')

Generator function

function* myGen(){ yield 1; }

The actual and formal parameters of a function

  • A formal parameter is a variable that we list when we define a function .
  • Arguments are the values we pass to the function when we call it .

image

Function parameters are specified when the function is defined , And all types of functions can have formal parameters .

Excerpt from : [ beautiful ] John Resig Bear Bibeault Josip Maras. “JavaScript Ninja Secret ( The first 2 edition ).” iBooks.

  • Function declaration (skulk Functional ninja Shape parameter ).
  • Function expression (performAction Functional person and action Shape parameter ).
  • Arrow function ( Shape parameter daimyo).

On the other hand , The argument is related to the call of the function . They are the values passed to the function when the function is called .

  • character string Hattori Pass to a function in the form of a function argument skulk.
  • character string Oda Nobunaga Pass to a function in the form of a function argument rule.
  • skulk The formal parameter of the function ninja Pass as an argument to a function performAction.
It can be understood in this way :
Function declaration and function expression , Arrow function , In the declaration, there are formal parameters in brackets ,
When a function is called , The arguments passed to the function are

The remaining parameters

function multiMax(first, ...remainingNumbers) { ⇽--- The remaining parameters are … Prefix
var sorted = remainingNumbers.sort(function(a, b) {
return b – a; ⇽--- Sort the remaining parameters in descending order
});
return first * sorted[0];
}
assert(multiMax(3, 1, 2, 3) == 9, ⇽--- Function calls are similar to other functions
"3*3=9 (First arg, by largest.)")

Prefix the last named argument of the function with an ellipsis (...) Prefix , This parameter becomes an array called the remaining parameters , The array contains the remaining parameters passed in .

Be careful ️: Only the last parameter of a function can be a residual parameter .

ES6 How to handle default parameters in

function performAction(ninja, action = "skulking"){ ⇽--- ES6 You can assign values to the formal parameters of a function
return ninja + " " + action;
}
assert(performAction("Fuma") === "Fuma skulking",
"The default value is used for Fuma");
assert(performAction("Yoshi") === "Yoshi skulking",
"The default value is used for Yoshi");
assert(performAction("Hattori") === "Hattori skulking",
"The default value is used for Hattori"); ⇽--- If there is no input value , Use default parameters
assert(performAction("Yagyu", "sneaking") === "Yagyu sneaking",
"Yagyu can do whatever he pleases, even sneak!"); ⇽--- Using the parameters passed in 

Summary

  • hold JavaScript As a functional language, you can write complex code .
  • As the first kind of object , Functions and JavaScript Same as other objects in . Similar to other object types , Function has the following functions .
  • Create... By literals .
  • Assign to a variable or property .
  • Pass as a function parameter .
  • Return... As the result of the function .
  • Assign values to properties and methods .
  • The callback function is followed by the code “ Come back and call ” Function of , It's a very common function , Especially in the event processing scenario .
  • Functions have properties , And these properties can be used to store any information , We can use this feature to do a lot of things ; for example :
  • You can store another function in the function properties for subsequent references and calls .
  • You can create a cache with function properties ( memory ), Used to reduce unnecessary calculations .
  • There are many different types of functions : Function declaration 、 Function expression 、 Arrow function and function generator, etc .
  • Function declaration and function expression are the two main types of functions . Function declaration must have function name , It must also exist as a separate statement in the code . A function expression may not have to have a function name , But at this point it has to be part of other statements .
  • The arrow function is JavaScript A new feature of ,“ This feature allows us to define functions in a more concise way .
  • When the definition of a function is a variable , The argument is the value passed to the function when the function is called .
  • The length of the formal parameter list and the argument list of the function can be different .
  • An unassigned parameter is evaluated to get undefined.
  • The extra arguments passed in are not assigned to any of the named parameters .
  • The remaining and default parameters are JavaScript New features .
  • The remaining parameters —— Additional arguments that do not match any parameter name can be referenced by the remaining arguments .
  • Default parameters —— When a function is called , If no parameters are passed in , The default parameter can give the function the default parameter value .
Excerpt from : [ beautiful ] John Resig Bear Bibeault Josip Maras. “JavaScript Ninja Secret ( The first 2 edition ).” iBooks.
版权声明
本文为[Oh, ha ha]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple