current position:Home>[front end three swordsmen III] analysis of JavaScript scalpel Part II

[front end three swordsmen III] analysis of JavaScript scalpel Part II

2022-04-29 06:40:48Ten leaves Zhiqiu

One 、 function

Pudong is Shanghai , Shanghai is Pudong

   What is a function ? Function in Java It's called method in . So said , Function is method , The method is the function . But there are some nuances .

They are the same thing , But there are different waistcoats
Usually , Without considering the difference between the two concepts . But if you have to consider , It can be understood in this way :

  • function , Is and “ object " Separate code snippets .
  • Method , Are snippets of code that rely on objects . Method => Member functions
    stay Java in , Because such code fragments are based on classes and objects . therefore Java They are all called " Method ".

1. Grammar format

/  Create a function / Function declaration / Function definition 
function  Function name ( Parameter list ) {
	 The body of the function 
	return  Return value ;
//  Function call 
 Function name ( Argument list ) //  Regardless of the return value 
 Return value  =  Function name ( Argument list ) //  Consider the return value 
  • There is no need to write the return value type ,
  • In the formal parameter list , You don't need to write parameter types

Example 1 : The function definition does not execute the function body content , Must be called to execute . Call several times and execute several times

        function hello(){
  • When calling a function, enter the function to execute , At the end of the function, return to the calling position and continue to execute . You can use the debugger to observe .
  • The definition of functions and the order of calls are not required . ( This is different from variables , Variables must be defined before they can be used )

2. Number of parameters

The number of arguments and formal parameters can not match . However, the actual development generally requires the number of formal parameters and actual parameters to match .

(1) Example 1 : If the number of arguments is less than the number of formal parameters , Then the extra formal parameter value is undefined

        function add(a,b,c,d,e,f,g){
            return a + b + c + d + e + f + g;

 Insert picture description here

   If you want to print normally here , Need to add a judgment , Namely a Whether it is not defined to , If it is , Is set to 0;

        function add(a,b,c,d,e,f,g){
            a = a||0;
            b = b||0;
            c = c||0;
            d = d||0;
            e = e||0
            f = f||0;
            g = g||0;
            return a + b + c + d + e + f + g;

that , Now you can print normally .
 Insert picture description here

(2) Example 2 : If the number of arguments is more than the number of formal parameters , Then the extra parameters do not participate in the function operation

        function add(a,b){
            a = a||0;
            b = b||0;
            return a + b ;

You can see , Although you pass a lot of parameters , But I have only two formal parameters , Data that can only count two arguments , Whatever comes out of it .
 Insert picture description here

   If we want to splice strings , What to do with that ?

   If you want your code , It can not only support the addition of numbers , It also supports string addition , At this time, it is necessary to judge .
   Determine the first parameter , Is it a string or a number .(JS, typeof), Through the type of the first parameter , To determine the default value of subsequent parameters , yes 0. still "" .

3. Function expression

   stay JavaScript in , Functions are first class citizens . function , Just like an ordinary variable , Can be assigned to other variables . It can also be used as an argument to another function , It can also be used as the return value of another function …

   Functions and ordinary variables , There is no essential difference , But variables such as functions have more functions than ordinary variables , Is callable .

   What is a function expression ?

Function expression is to assign a function to a variable .

        function hello(){
        let f = hello;
		//console.log(typeof f);// Through this line of statement, you can see f The type of 
        // adopt f You can call the above function 

 Insert picture description here
The above wording can also be changed to :

 let f = function hello(){

And it can be changed into the following :

let f = function(){

   At this point, a function without a name is defined , be called " Anonymous functions ", There's another name , lambda expression . And form like function() { } This way of writing defines an anonymous function , Then the anonymous function is represented by a variable . You can go through this in the back f Variable to call the function

4. Scope

Scope refers to the valid range of an identifier name in the code .

stay ES6 Before standard , The scope is mainly divided into two

  1. Global scope : Throughout script In the label , Or alone js In document .
  2. Local scope / Function scope : Take effect inside the function .
        let num = 10;

        function test1(){
            // local variable 
            let num =20;

        function test2(){
            // local variable 
            let num =30;


 Insert picture description here

If you don't write... When creating variables var perhaps let, Then you get a global variable , Such as :

        function test(){
            num =20;

 Insert picture description here

5. Scope chain

  • Functions can be defined inside functions
  • The inner function can access the local variables of the outer function
        let num = 10;
        function hello(){
            function hello1(){

  JS Scope in , It's supporting " Step by step up " Look for , The above code is currently in hello1 In this function , Try printing num. But in hello1 in , No, num Variable . So he went to his superior , eureka hello Function here , But in hello in , either num, So continue to look up , Found global scope . eureka num, If the last global scope is not found , You're going to report a mistake .

Two 、 object

1. Basic concepts

An object is a specific thing ,“ Book ” Not object , But a generic category . and “ My book ” It's an object

   stay JavaScript in , character string , The number , Array , Functions are objects . Each object contains several properties and methods .

  • attribute : The characteristics of things .
  • Method : The behavior of things .

   If you have a pet dog , The weight of the dog , Height these are attributes , And it will pick up things , Can sing these are all ways .

   The object needs to save multiple properties , Although arrays can also be used to hold multiple data , But not good enough . For example, it represents a student's information . ( Name: Cai Xukun , height 175cm, weight 170 Jin ).var student = [‘ Cai Xukun: A boy devoted to music in "More than Forever" ’, 175, 170]; But in this case 175 and 170 Who means height , Who says weight , It's easy to distinguish .

   And Java Differences between objects in :

  • stay Java in , object , There is a need for , Then the instantiation of the class produces the object .Java in , Class can be regarded as a custom type .(Cat Classes and Dog Class two different types )
  • JavaScript in , Objects are not class dependent , stay JavaScript All the objects in , It's all one type . object

2. Create an object using literals [ Commonly used ]

 Use  {
     }  Create objects 
 let student = {
            name: ' Bored, bored ',
            age: 25,
            height: 175,
            weight: 124,

                console.log(" Cheap mouth ");
            sing: function(){
                console.log(" Northeast Folk Songs ")
  • Use { } Create objects
  • Properties and methods are organized in the form of key value pairs .
  • Use... Between key value pairs , Division . After the last attribute , not essential
  • Use... Between key and value : Division .
  • The value of the method is an anonymous function

Use the properties and methods of the object :

//1.  Use  .  Member access operators to access properties  `.`  Can be interpreted as  " Of "
// 2.  Use  [ ]  Access properties ,  In this case, the attribute needs to be quoted  
// 3.  Calling method ,  Don't forget to add  () 

 Insert picture description here

3. Use new Object Create objects

        let student = new Object(); = " Dead dead ";
        student.height = 175;
        student['weight'] = 140;
        student.sing = function(){
            console.log(" Songs from all over the world ");

  • Use { } The created object can also be used at any time = “ Cai Xukun: A boy devoted to music in "More than Forever" ”; This is the way to add new attributes

 Insert picture description here

4. Use constructors to create objects

   At present, what we call constructor , In fact, it is a special function to create a group of similar objects in batch .

Basic grammar :

function  Constructor name ( Shape parameter ) {
this. attribute  =  value ;
this. Method  = function...
var obj = new  Constructor name ( Actual parameters );
  • Use inside a constructor this Keyword to represent the object currently being built , When you see the inside of a function , adopt this. When creating attributes in this way , At this point, the function has a high probability of being a constructor

  • The function name of the constructor is usually capitalized .

  • The function name of the constructor can be a noun .

  • Constructors don't need return

  • When creating objects, you must use new keyword .

example : Recreate the cat object using the constructor

        function Cat(name,type,sound){
   = name;
            this.type = type;
            this.miao = function(){

        var mimi = new Cat(' Mimi ',' Chinese country cat ',' meow ')
        var xiaohei = new Cat(' Little black ', ' Persian meow ', ' Cat whine ');
        var ciqiu = new Cat(' Prick ball ', ' The golden hierarchy ', ' Gollum ');


 Insert picture description here

5. understand new keyword

new Implementation process of :

  1. First create an empty object in memory { }
  2. this Point to the empty object just now ( Take the object of the previous step as this The context of )
  3. Code to execute the constructor , Create properties and methods for objects
  4. Return this object ( The constructor itself does not need return, from new take the trouble for )

6.JavaScript The object and Java Difference of objects

(1) JavaScript No, “ class ” The concept of

   The object is “ attribute ” + “ Method ” . Class is equivalent to extracting the attributes and methods of some common objects separately , Equivalent to one “ Moon cake mold ”.
   stay JavaScript Medium “ Constructors ” It can also have a similar effect . And even if it's not a constructor , You can also pass at any time { } Specify some objects in a way stay
  ES6 It also introduces class keyword , Can follow a pattern similar to Java To create classes and objects .

(2)JavaScript Object indistinguishable “ attribute ” and “ Method ”

JavaScript The function in is “ First class citizen ”, Just like ordinary variables . Variables that store functions can be passed through ( ) To call and execute .

(3)JavaScript Objects have no private / public And other access control mechanisms

The properties in the object can be accessed by the outside world at will .

(4)JavaScript Objects have no “ Inherit ”

   The essence of inheritance is “ Associate two objects ”. Or let one object reuse the properties of another object / Method . JavaScript Use in “ Prototype ” The mechanism achieves a similar effect

(5)JavaScript No, “ polymorphic ”

   The essence of polymorphism is “ Program apes don't have to focus on specific types , You can use one of these methods ”.,
C++ / Java And other statically typed languages have strict type constraints and verification . Therefore, inherit the parent class through subclasses , And override the side of the parent class The way of law To achieve the effect of polymorphism . But in JavaScript The type itself is dynamically supported , When using a method of an object, the program itself does not need to control the object Make a clear distinction between types .
   Therefore, there is no need to support polymorphism at the grammatical level .

for instance :

stay Java I have learned ArrayList and LinkedList. In order to make the program easy to use , Often write :

List<String> list = new ArrayList<>()

Then we can write a method :

void add(List<String> list, String s) {

We don't have to focus on list yes ArrayList still LinkedList, As long as it is List Just go . because List Inside there is add Method .
And when we use JavaScript When it comes to code :

function add(list, s) {

  add about list The type of this parameter itself has no restrictions . It only needs list This object has add The method can . You don't have to be like Java In that way, inherit first and then rewrite. Go around in a circle .

3、 ... and 、 understand WebAPI

1. What is? WebAPI

JavaScript Divided into three parts :

  • ECMAScript: Basic grammar part
  • DOM API: Operation page structure
  • BOM API: Operating the browser

WebAPI contains DOM + BOM

   If you want to write a more complex interactive page , Not only the basic grammar , It also needs to be WebAPI Support for .

2.API What is it?

API It's a broader concept . and WebAPI It's a more specific concept , especially DOM+BOM. So-called API It is essentially some ready-made functions / object , Let the program ape take it and use it , Easy to develop .

API It's like a toolbox . It's just that there are a large number of toolboxes used by program apes , Complex functions .

API Reference documents :API Reference documents

3. understand DOM

3.1.DOM What is it?

DOM Its full name is Document Object Model.

W3C The standard provides us with a series of functions , Let's operate :

  • Web content
  • Web page structure
  • Web page style

The page structure is like :

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title> Sample page </title>
	<h2> This is a sample page </h2>
	<p id="p" title="this is p."> This is a paragraph .</p>

DOM The tree structure is as follows :

 Insert picture description here

Here are some important , We need to understand the concept of :

  • file : A page is a file , Use document Express .
  • Elements : All tags in the page are called Elements . Use element Express .
  • node : All the content in a web page can be called node ( Tag node , Comment node , Text node , Attribute nodes, etc ). Use node Express .

These documents and other concepts are in JS The code corresponds to objects one by one , That's why it's called “ Document object model ”.

Four 、 Get elements

   Get elements . Use DOM The basis of . To manipulate elements on a page , You need to get the corresponding JS object .DOM A set of API Can get the elements of the web page . Here are just two of the most important :querySelector and querySelectorAll.


   Getting elements here is similar to CSS Function of selector , Use querySelector Be able to completely reuse what I learned earlier CSS Selector knowledge , Achieve a faster and more accurate way to obtain element objects .

Obtain by :

var element = document.querySelector(selectors);

analysis :

  • document The properties of such an object . Is the global object in the page . A page is loaded , A global variable is generated automatically , It's called document . There are some properties and methods , Let's manipulate the content of the page .

  • selectors Containing one or more selectors to match DOM character string DOMString . The string must be valid

  • CSS Selector string ; If not , The cause SYNTAX_ERR abnormal
    Represents a set of documents with a specified set of CSS The of the first element that the selector matches html Elements Element object .

  • If you need a list of all elements that match the specified selector , Should be used querySelectorAll()

  • You can call... On any element , not only document. The element calling this method will be the root element of this search

Just because the parameter is a selector , So be sure to specify what kind of selector it is through special symbols , As in the following example .box Is a class selector , #star yes id Selectors etc. .

        let elem1 = document.querySelector('.box');
        let elem2 = document.querySelector('#id');
        let elem3 = document.querySelector('h3 span input');

    <div class="box">abc</div>
    <div id = "id">123</div>
            <input type="text" name="" id="">

 Insert picture description here


        let obj = document.querySelectorAll('ul li');

 Insert picture description here
   Accurately speaking , querySelectorAll What is returned is not a real native array . It's an object . It's just this object , Yes length, You can also access internal elements by subscript , Such objects are very similar to arrays ( As like as two peas ), be called “ Pseudo array ".

5、 ... and 、 Last words

   I've been sleepy lately , At the same time, I'm almost finished reading the brief history of mankind , I've really been reading this book for a year , The heart is not still , I'm tired of reading a page or two . Recently I feel , No peace of mind , Sometimes there is a sense of meaninglessness , So I want to find some meaning in the book .

copyright notice
author[Ten leaves Zhiqiu],Please bring the original link to reprint, thank you.

Random recommended