Introduction to object oriented programming
Process oriented is to analyze the steps needed to solve the problem, and then use functions to implement these steps step by step. When using, you can call them one by one
Object oriented is to decompose transactions into objects, and then divide and cooperate among objects.
Object oriented is to divide problems by object functions, not steps
In the idea of object-oriented program development, each object is the function center and has a clear division of labor.
Object oriented programming has the advantages of flexibility, code reusability, easy maintenance and development. It is more suitable for large-scale software projects with multi person cooperation.
Object oriented features
- Encapsulation
- Inheritance
- Polymorphism
Comparison between object oriented and process oriented
Process oriented
- Advantages: higher performance than object-oriented, suitable for things closely related to hardware, such as process oriented compilation adopted by single chip microcomputer‘
- Disadvantages: no object-oriented, easy to maintain, easy to reuse and easy to expand
object-oriented
- Advantages: easy to maintain, easy to use and easy to expand. Due to the characteristics of object-oriented encapsulation, inheritance and polymorphism, a low coupling system can be designed to make the system more flexible and easier to maintain
- Disadvantages: lower performance than process oriented
class
Nature of class
The function of a class is a function function. We can also simply think that a class is another way to write a constructor
-
Class has prototype object prototype
-
Class also has a prototype object prototype, which has a constructor pointing to the class itself
-
Class can add methods through prototype objects
-
Star.prototype.sing = function(){};
The essence of ES6 is grammar sugar
Class and object oriented
Object oriented thinking characteristics
- Extract (Abstract) the attributes and behaviors shared by objects, organize (encapsulate) them into a class (template)
- Instantiate the class to get the object of the class
object
Objects are composed of properties and methods
- Attribute: the characteristic of a thing, which is represented by an attribute in an object (a common noun)
- Method: the behavior of things is expressed by means in the object (commonly used verb)
class
Class abstracts the common part of an object. It generally refers to a large class
Object refers specifically to a specific object that is instantiated through a class
Create classes in ES6
grammar
class name{ //class body }
Create instance
let xx = new name();
Note: the class must instantiate the object with new
// 1. Create class create a star class class Star { constructor(uname,age) { this.uname = uname; this.age = age; } } // 2. Create new object with class let ldh = new Star("Lau Andy",20); let zxy = new Star('Xue You Zhang',60); console.log(ldh.uname); //Lau Andy console.log(zxy.uname); //Xue You Zhang
Class constructor constructor
The constructor() method is the constructor of the class (the default method). It is used to pass parameters and return the instance object. When the object instance is generated through the new command, this method will be called automatically. If there is no display definition, a constructor() will be automatically created inside the class
Considerations for creating classes
- Create a class through the class keyword. We still habitually define the initial capitalization of the class name
- Class has a constructor function, which can accept the passed parameters and return the instance object at the same time
- constructor function will automatically call this function as long as new generates an instance. If we don't write this function, the class will automatically generate this function.
- The generated instance new cannot be ignored
- Finally, pay attention to the syntax specification. Do not add parentheses after the class name of the created class, open parentheses after the generated instance type, and do not add function to the constructor
Class
- All functions in our class do not need to write function
- Multiple function methods do not need to be separated by commas
<script> // 1. Create class create a star class class Star { constructor(uname, age) { this.uname = uname; this.age = age; } sing(song) { console.log(this.uname + "sing" + song); } } // 2. Create new object with class let ldh = new Star("Lau Andy", 20); let zxy = new Star("Xue You Zhang", 60); console.log(ldh.uname); //Lau Andy console.log(zxy.uname); //Xue You Zhang ldh.sing("Ice rain"); zxy.sing("Li Xianglan"); </script>
Class inheritance
// 1. Class inheritance class Father { constructor() {} money() { console.log(100); } } class Son extends Father {} let son = new Son(); son.money();//100 son.money();//100
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
class Father{ constructor(x,y){ this.x = x; this.y = y; } sum(){ console.log(this.x+this,y); } } class Son{ constructor(x,y){ //this.x = x; //this.y = y; This is wrong //The constructor in the parent class was called super(x,y); } } let son = new Son(100,30); son.sum();//130
The reason is that x and y in son are different from father
super()
super() calls ordinary functions of the parent class and the search principle of attribute methods in inheritance
// super class Father{ say(){ console.log("I'm your father"); } } // class Son{ // say(){ // console.log('I'm your son '); // } // } // let son =new Son(); // son.say(); // I'm your son class Son extends Father{ say(){ //console.log('I'm your son '); console.log(super.say()) //son. I'm your father } } let son =new Son(); son.say(); //I'm your son
- In inheritance, if you instantiate a subclass to output a method, first see whether the subclass has this method. If so, execute the subclass first
- In inheritance, if there is no method in the subclass, check whether the parent class has this method. If so, execute the method of the parent class (proximity principle)
super must be placed before the subclass this
The following code is to ensure that the attributes of the parent class are inherited and the attributes of the child class are appended at the same time.
class Father { constructor(x, y) { this.x = x; this.y = y; } } class Son extends Father { constructor(x, y) { // Using super to call the constructor in the parent class super(x, y); this.x = x; this.y = y; //super(x, y); If an error is reported after this, you should first call the constructor in the parent class and then this, } subtract() { console.log(this.x - this.y); } } let son = new Son(5, 3); son.subtract(); //2
Note: the subclass constructor uses super and must be placed before this (the constructor of the parent class must be called first, and then the constructor of the subclass)
Classes and objects
Four points for attention:
- In ES6, there is no variable promotion for a class, so you must define a class before you can instantiate an object through the class
- The common properties and methods in the class must be used with this
- this in the class points to the problem
- This in the constructor points to the instance object, and this in the method points to the caller of this method
constructor Inside this Refers to the instance object created
The direction of this
<button id="btn">Button</button> <script> let that; let _that; class Star { //this in the constructor refers to the created instance object constructor(uname, age) { that = this; console.log(this); this.uname = uname; this.age = age; // this.sing() //undefined this.btn = document.getElementById("btn"); this.btn.onclick = this.sing; } sing() { // This in the sing method points to the btn button, because the button calls this function console.log(this); console.log(this.uname); //undefined console.log(that.uname) //Lau Andy } dance() { // This in dance refers to the instance object ldh, because ldh calls this function _that = this; console.log(this); } } let ldh = new Star("Lau Andy"); ldh.dance();//Subject {uname: "Andy Lau", age: undefined, btn: button#btn} </script>
Object oriented tab bar (case)
Thinking analysis and layout
Add label bar dynamically
Functional requirements:
- Click the tab bar to switch the effect
- Click the + sign to add tab items and content items
- Click the x sign to delete the current tab item and modify the text content
- Double click the text of tab item or content item to modify the text content
Switching function:
css, content and Title Interaction
Add features:
- Create li element and section element
- Append the technological element to the corresponding parent element
Constructors and prototypes
Using constructors
Constructor is a special function, which is mainly used to initialize the object, that is, assign the initial value to the object member variable. It is always used with new. We can extract some common items and methods from the object and encapsulate them in this function
In js, you should pay attention to the following two points when using constructors:
- Constructors are used to create a class of objects whose first letter should be capitalized.
- Constructors need to be used with new to make sense
new does four things when pointing
- Create a new empty object in memory
- Let this point to the new object
- Execute the code in the constructor to add properties and methods to the new object.
- Return this new object (so return is not required in the constructor)
<script> let obj1 = new Object(); let obj2 = {}; // Creating objects with constructors function Star(uname, age) { this.uname = uname; this.age = age; this.sing = function() { console.log("I can sing"); }; } let ldh = new Star("Lau Andy", 18); console.log(ldh); //Object {uname: "Andy Lau", age: 18, sing: sing()} ldh.sing();//I can sing </script>
The properties and methods in the constructor are called members, and members can be added
Instance members are members added through this inside the constructor
Instance members can only be accessed through instantiated objects
Instance members cannot be accessed through constructors
Static members add members to the constructor itself. sex is a static member
Static members can only be accessed through constructors, not objects
Star.sex="male"; console.log(Star.sex);//male console.log(ldh.sex); //undefined
Constructor problem
Constructor method is very easy to use. It is a waste of memory.
<script> // 1. Function problem of constructor function Star(uname, age) { this.uname = uname; this.age = age; this.sing = function() { console.log("001"); }; } let ldh = new Star("Lau Andy", 18); let zxy = new Star("Xue You Zhang", 20); console.log(ldh.sing === zxy.sing);//false </script>
Constructor prototype
Constructors allocate functions through prototypes that are shared by all objects
JavaScript stipulates that each constructor has a prototype attribute, pointing to another top-down. Note that this prototype is an object, and all properties and methods of this object will be owned by the constructor.
We can define those invariant methods directly on the prototype object, so that all object instances can share these methods.
<script> // 1. Function problem of constructor function Star(uname, age) { this.uname = uname; this.age = age; // this.sing = function() { // console.log("001"); // }; } Star.prototype.sing = function() { console.log("001"); }; let ldh = new Star("Lau Andy", 18); let zxy = new Star("Xue You Zhang", 20); console.log(ldh.sing === zxy.sing); //true // 2. In general, our public properties are defined in the constructor, and the public methods are placed on the prototype object </script>
Constructor constructor
Object prototype (proto_) And the prototype object of the constructor have a property constructor property. Constructor is called the constructor because it refers to the constructor itself.
In many cases, we need to manually use the constructor attribute to refer to the original constructor
If we modify the original prototype object and assign an object to the prototype object, we must manually use the constructor to refer back to the original constructor.
<script> // 1. Function problem of constructor function Star(uname, age) { this.uname = uname; this.age = age; // this.sing = function() { // console.log("001"); // }; } // Star.prototype.sing = function() { // console.log("001"); // }; // Star.prototype.movie = function(){ // console.log() // } Star.prototype = { contructor: Star, sing: function() { console.log("I can sing"); }, movie: function() { console.log("I can play movies!"); }, }; let ldh = new Star("Lau Andy", 18); let zxy = new Star("Xue You Zhang", 20); // console.log(ldh.sing === zxy.sing); //true console.log(Star.prototype.contructor); console.log(ldh.__proto__.contructor); // 2. In general, our public properties are defined in the constructor, and the public methods are placed on the prototype object </script>
The relationship among constructor, instance and prototype object
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-orqacqte-164286577061) (C: \ users \ 26870 \ desktop \ 002. PNG)]
Member lookup mechanism of JavaScript
- When accessing the object properties (including methods) of an object, first find out whether the object itself has the property.
- If not, find its prototype (i.e. _proto_) Prototype object pointed to)
- If not, find the prototype of the Object (the prototype Object of the Object)
- And so on until the Object is found (null)
function Star(uname, age) { this.uname = uname; this.age = age; } Star.prototype.sing = function() { console.log("I can sing"); }; Star.prototype.sex = "female"; let ldh = new Star("Lau Andy", 18); ldh.sex = "male"; console.log(ldh.sex); //Principle of male proximity console.log(Object.prototype); //Object { ... } console.log(ldh); //Object {uname: "Andy Lau", age: 18, sex: "male"} console.log(Star.prototype);//Object { sing: sing()
this point in prototype object
- In the constructor, this refers to an object instance
- this in the prototype object refers to the instance object
<script> function Star(uname, age) { this.uname = uname; this.age = age; } let that; Star.prototype.sing = function() { console.log("I can sing"); that = this; }; let ldh = new Star("Lau Andy", 20); // 1. In the constructor, this refers to the object instance ldh ldh.sing(); //I can sing console.log(that); //Object {uname: "Andy Lau", age: 20} console.log(that === ldh); //true; // 2. this in the prototype object refers to the instance object ldh </script>
Extend built-in objects
You can extend and customize the original built-in object through the prototype object. For example, add a custom even sum function to the array
// Application extension built-in object method of prototype object console.log(Array.prototype); Array.prototype.sum = function() { let sum = 0; for (let i = 0; i < this.this.length; i++) { sum += this[i]; } return sum; };
You can't write the following code because it overwrites all the prototype s
Array.prototype={ sum:function(){ let sum = 0; for (let i = 0; i < this.this.length; i++) { sum += this[i]; } return sum; } }
Characteristics of constructors
- Constructor has prototype object prototype
- The constructor prototype object prototype has a constructor pointing to the constructor itself
- Constructors can add methods through prototype objects
- The instance object created by the constructor has __ proto_ __ The prototype points to the prototype object of the constructor
inherit
ES6 did not provide us with extensions inheritance before. We can implement inheritance through constructor + prototype object simulation, which is called composite inheritance
call()
Disable this function and modify the this point when the function runs
fun.call(this.Arg,arg1,arg2,.....)
- thisArg: currently calls the pointing object with function this.
- arg1, arg2: other parameters passed
// call method function Fu(x, y) { console.log("001"); console.log(this); //window console.log(x + y); // } let o = { name: "ludan", }; // Fu(); //001 window NaN // 1. call() can call a function // Fu.call(); //001 window NaN // 2. call() can change the point of this of this function, and this of this function points to o this object Fu.call(o, 1, 2); //001 Object { name: "ludan" } 3
Inheriting parent class attributes by constructing cold elements
Core principle: point this of the parent type to this of the child type through call(), so that the child type can inherit the properties of the parent type.
Who points this to
// Inherit properties by borrowing the parent constructor // 1. Parent constructor function Father(uname, age) { // this points to the object instance of the parent constructor this.uname = uname; this.age = age; } // 2. Sub constructor function Son(uname, age, score) { // this points to the object instance of the child constructor Father.call(this, uname, age); this.score = score; } let son = new Son("Lau Andy", 20, 100); console.log(son); //Object {uname: "Andy Lau", age: 20, score: 100}
Using prototype object inheritance method
// Inherit properties by borrowing the parent constructor // 1. Parent constructor function Father(uname, age) { // this points to the object instance of the parent constructor this.uname = uname; this.age = age; } Father.prototype.money = function() { console.log("1000000"); }; // 2. Child constructor function Son(uname, age, score) { // this points to the object instance of the child constructor Father.call(this, uname, age); this.score = score; } Son.prototype = new Father(); // If you modify the prototype object in the form of an object, don't forget to use the constructor to refer back to the original constructor Son.prototype.constructor = Son; //Child constructors are specialized methods Son.prototype.exam = function() { console.log("Children don't want to learn"); }; //This covers // Son.prototype = Father.prototype; // If the child prototype object is modified, the parent prototype object will also change let son = new Son("Lau Andy", 20, 100); console.log(son); //Object {uname: "Andy Lau", age: 20, score: 100} son.money(); //1000000 console.log(Son.prototype.constructor); //function Son(uname, age, score)
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-17w8pi2s-164286577062) (C: \ users \ 26870 \ desktop \ 003. PNG)]
New methods in ES5
Array method
Iterative (traversal) methods: forEach(), map(), filter(), some(), every();
forEach()
array.forEach(function(currentValue,index,arr))
Parameters:
- currentValue: the value of the current item of the array
- Index: the index of the current item of the array
- arr: array object itself
let arr = [1, 2, 3]; let sum = 0; arr.forEach(function(value, index, array) { console.log("Each array element" + value); console.log("Index number of each array element" + index); console.log("Array itself" + array); sum += value; }); console.log(sum);
filter() filter array
array.filter(function(currentValue,index,arr))
-
The filter() method creates a new array. The rage in the new array is mainly used to filter the array by checking all qualified elements in the specified array
-
Notice that it returns a new array directly
Parameters:
- currentValue: the value of the current item of the array
- Index: the index of the current item of the array
- arr: array object itself
<script> let arr = [12, 36, 4, 88]; var newArr = arr.filter(function(value, index) { return value >= 20; }); console.log(newArr); //Array [ 36, 88 ] </script> </body>
Returns an array
some()
- some() method is used to detect whether the elements in the array meet the specified conditions, and click to find whether there are elements in the array that meet the conditions
- Note that its return value is Boolean. If this element is found, it will return true. If it is not found, it will return false
- If a qualified element is found, the loop is terminated and the search is no longer continued
- Parameters:
- currentValue: the value of the current item of the array
- Index: the index of the current item of the array
- arr: array object itself
let arr = [11, 6, 89, 10]; let flag = arr.some(function(value) { return value < 3; }); console.log(flag); //false let arr1 = ["red", "pink", "blue"]; let flag1 = arr1.some(function(value) { return value == "pink"; }); console.log(flag1); //true
Returns a Boolean value
New cases using array
<body> <div class="find" align="center"> <div> Query by price:<input class="start" />-<input type="text" class="end" /> <button id="btn01">search</button> Query by commodity name:<input type="text" class="name" /> <button id="btn02">query</button> </div> <table align="center" border="1px" width="400px"> <thead> <th>id</th> <th>Product name</th> <th>Price</th> </thead> <tbody align="center"></tbody> </table> </div> <script> let data = [{ id: 1, pname: "millet", prices: 2999, }, { id: 2, pname: "Huawei", prices: 4999, }, { id: 3, pname: "oppo", prices: 3999, }, { id: 4, pname: "millet", prices: 1999, }, ]; // Get the corresponding element let tbody = document.querySelector("tbody"); let btn01 = document.querySelector("#btn01"); let start = document.querySelector(".start"); let end = document.querySelector(".end"); let btn02 = document.querySelector("#btn02"); let name = document.querySelector(".name"); // Render data to the page setData(data); function setData(myData) { // Empty the original rendering first tbody.innerHTML = ""; myData.forEach(function(value) { let tr = document.createElement("tr"); tr.innerHTML = "<td>" + value.id + "</td><td>" + value.pname + "</td><td>" + value.prices + "</td>"; value.prices + "</td>"; tbody.appendChild(tr); }); } // 3. Query goods by button // When we click the button, we can filter the objects in the array according to our commodity price btn01.addEventListener("click", function() { let newData = data.filter(function(value) { return value.prices >= start.value && value.prices <= end.value; }); setData(newData); }); // Render the filtered objects to the page // 4. According to the commodity name btn02.addEventListener("click", function() { let newData02 = data.filter(function(value) { return value.pname == name.value; }); setData(newData02); }); </script> </body>
String method
trim()
The trim() method deletes an empty string from both ends of a string
str.trim();
The trim() method does not affect the original spontaneous formation itself. It returns a new string
charCodeAt()
This method can view the character encoding of the specified symbol. This method returns the symbol value of the specified index position, and the index is specified as an integer.
let message = 'acbddf'; console.log(message.charCodeAt(2)); //99
String operation method
concat()
Splices one or more strings into a new string
concat() can accept any number of parameters at once, so you can splice multiple strings at once
Put back value: a new string
slice()
The slice() method extracts a part of a string and returns the extracted part with a new string.
stringObject.slice(start,end)
Return value
A new string. The string stringObject includes all characters from start (including start) to end (excluding end).
Object method
Objct.defineProperty() defines a new property or modifies an existing property in an object.
Object.defineProperty(obj,prop,descriptor)
- obj: required. Target object
- prop: required. The name of the attribute to be defined or modified
- descriptor: required. Attributes owned by the target attribute.
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-perfmkr0-164286577063) (C: \ users \ 26870 \ desktop \ 005. PNG)]
let obj = { id: 1, num: 1000, price: 1909, }; Object.defineProperty(obj, "num", { value: 1000, }); Object.defineProperty(obj, "id", { // If false, this property value is not allowed to be modified writable: false, });
Delete delete
function
How functions are defined
- Function declaration mode function (keyword) (named function)
- Expression for function (anonymous function)
- Use new Function('parameter 1 ',' parameter 2 ',' function body '); Function , must be in the form of string
- Function is inefficient and inconvenient to write, so it is rarely used
- All functions are instances (objects) of functions
- Functions also belong to objects
// 1. Custom function (named function) function fu(){} // 2. Expression for function (anonymous function) let fun = function(){} // 3. Use new Function('parameter 1 ',' parameter 2 ',' function body '); let f = new Function('a','b','console.log(a+b)'); f(1,2);
Function call
Function call mode
- Ordinary function
- Object method
- Constructor
- Binding event function
- Timer function‘
- Execute function now
// 1. The normal function this points to window function fu(){ console.log(123); } fu(); //Or Fu call() // 2. Object method this points to o let o ={ sayHi:function(){ console.log(123); } } o.sayHi(); // 3. The constructor this points to the instance object. The prototype object's this also points to the instance object function Star(){}; new Star(); // 4. Binding event function this points to btn btn.onclick = function(){}; //Click the button to call // 5. Timer function this points to window setInterval(function(){},1000); //This function is called every 1 second // 6. Execute function now this Point to window (function(){ console.log(123); })(); //The immediate function is called automatically
this point in function
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-hsoawc1e-164286577063) (C: \ users \ 26870 \ desktop \ 006. PNG)]
Change the direction of the function this
JavaScript provides us with some function methods to help us deal with the problem of this pointing inside the function more gracefully. Commonly used are bind(), call(), and apply()
call()
The call() method calls an object. It is simply understood as the way to call a function, but it can change the direction of this of the function
call is mainly used to implement inheritance
fun.call(thisArg,arg1,arg2);
let o = { name: "ludan", }; function fu(a, b) { console.log(this); console.log(a + b); } fu.call(o, 1, 2); //Object { name: "ludan" } 3 // call implementation inheritance function Father(uname, age, sex) { this.uname = uname; this.age = age; this.sex = sex; } function Son(uname, age, sex) { Father.call(Son, uname, age, sex); } let son = new Son("Lau Andy", 18, "male"); console.log(son); //Object { }
apply()
The apply() method calls a function. It is simply understood as the way to call a function, but it can change the direction of this of the function
fun.apply(thisArg,[argsArray]);
- thisArg: the value of this specified when the fun function runs
- argArray: the passed value must be included in the array
- The return value is the return value of the function, because it is the calling function
Its parameters must be arrays (pseudo arrays). Its main function is to find the maximum value with the help of mathematical built-in objects
let a = { name: "ludan", }; function fu(arr) { console.log(this); console.log(arr); } fu.apply(o, ["pink"]); //Object { name: "ludan" } pink // The main role of apply // Math.max(); let arr = [1, 66, 3, 99, 4]; let b = Math.max.apply(null, arr); console.log(b); //99
bind()
The bind() method does not call the function. But it can change the direction of this inside the function
fun.bind(thisArg,arg1,arg2)
- thisArg: the value of this specified when the fun function runs
- arg1,arg2: pass other parameters
- Returns a copy of the original function modified by the specified this value and initialization
Returns the new function generated after the original function is changed to this
If we don't need to call some functions immediately, but want to change the internal this point of this function, then use bind
<button></button> <script> let c = { name: "ludan", }; function f(a, b) { console.log(this); console.log(a + b); } let d = f.bind(c, 1, 2); d(); //Object { name: "ludan" } 3 // If we have a button, when we click it, we disable it and turn it on after 3 seconds let btn = document.querySelector("button"); btn.onclick = function() { // Disable button this.disabled = true; //This this points to btn this button setInterval( function() { this.disabled = false; //this in the timer points to window }.bind(this),3000); //this refers to the btn object }; </script>
Strict mode
Strict schema definition
The strict mode of ES5 is limited
Strict mode is only supported in browsers above IE10, and will be ignored in older browsers
Strict mode makes some changes to the normal JavaScript semantics:
- It eliminates some unreasonable and imprecise aspects of JavaScript syntax and reduces some strange behaviors
- It eliminates some unsafe places in code operation and ensures the safety of code operation
- Improve the efficiency of the compiler and increase the running speed
- Some grammars that may be defined in future versions of ECMAScript are disabled to pave the way for new versions of JavaScript. For example, keep some keywords: class, enum, export, extends, import and super, and cannot be used as variable names
Turn on strict mode
Strict patterns can be applied to entire scripts or individual functions. Therefore, when using strict mode, we can divide strict mode into script enabling strict mode and function enabling strict mode.
1. Turn strict mode on for scripts
To enable strict mode for the entire script file, you need to put a specific statement "use strict" before all statements; (or 'use strict')
<script> 'use strict'; // The following js code will execute the code in strict mode </script> <script> (function(){ 'use strict' })(); </script>
2. Turn on a strict mode for a function
<script> // At this time, it is only a strict mode for fn function fn(){ 'use strict'; // The following code follows a strict pattern } function fun(){ // It's still in the normal mode } </script>
Changes in strict mode
Strict mode has made some changes to the syntax and behavior of JavaScript
1. Variable specification
- In normal mode, if a strict variable has no declared assignment, it defaults to a global variable. Strict patterns prohibit this syntax, and variables must be declared before they are used
- We cannot delete declared variables at will, such as delete x; It's wrong
2. this pointing problem in strict mode
- Previously, this in the global scope function pointed to the window object
- In strict mode, this in the function in the global scope is undefined
- In the past, constructors can be called without new. When an ordinary function, this points to a global object
- In strict mode, if the constructor does not add a new call, this will report an error
- The constructor instantiated by new points to the creation of an object instance
- Does this of the timer point to window
- Event, object, or point to the caller
<script> "use strict"; // 1. Variables must be declared before use let num = 10; console.log(num); //10 // 2. We cannot delete declared variables at will // delete num; function fn() { console.log(this); //undefined; } fn(); function Star() { this.sex = "nan"; } // Star(); // console.log(window.sex); //this is undefined let a = new Star(); console.log(a.sex); //nan </script>
3. Function change
-
You cannot have arguments with duplicate names in a function
-
Functions must be declared at the top level. The latest version of JavaScript introduces "block level scope" (introduced in ES6). In order to adapt to the new version, it is not allowed to declare functions in non function code blocks
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-tqs5utvm-164286577064) (C: \ users \ 26870 \ desktop \ 007. PNG)]
Higher order function
**Higher order function * * is a function that operates on other functions. It receives functions as parameters and outputs functions as return values
<script> function fn(callback){ callback&&callback(); } fn(function(){alert('hi')}); </script>
<script> function fn(){ return function(){} } fn(); </script>
At this point fn is a higher order function
Function is also a data type. It can also be passed to another parameter as a parameter. The most typical is as a callback function
closure
A closure is a function that has access to a variable in the scope of another function.
A simple understanding is that a scope can access local variables inside another function
<script> // Closure: the scope of the function fun accesses the local variable num in another function fn function fn() { let num = 10; function fun() { console.log(num); } fun(); } fn(); //10 </script>
Variable scope
Variables can be divided into two types according to different scopes: global variables and local variables
- Global variables can be used inside functions
- Local variables cannot be used outside a function
- When the function is executed, the local variables in this scope will be destroyed
Function of closure
function fn() { let num = 10; function fun() { console.log(num); } return fun; } let f =fn(); f(); //10 // be similar to // let f = function fun() { // console.log(num); // }
The main function of closures is to extend the scope of variables
The immediate execution function is also called a small closure because any function in the immediate execution function can use its i variable
recursion
definition
If a function can call itself internally, then this function is a recursive function
Simple understanding: the function calls itself internally. This function is a recursive function
Recursive functions have the same effect as loops
Due to the "stack overflow" error of arbitrary recursion, the exit condition return must be added
let num = 0; function fn() { console.log("I want to print these six sentences"); if (num == 6) { return; //A recursive function must have an exit condition } num++; fn(); } fn();
Factorization of n by recursion
// Factorization of 1~n by recursive function function fn(n) { if (n == 1) { return 1; } return n * fn(n - 1); } console.log(fn(3)); //6 console.log(fn(4)); //24
Using recursive function to find Fibonacci sequence (rabbit sequence)
<script> // Using recursive function to find Fibonacci sequence (rabbit sequence) 1, 1, 2, 3, 5, 8, 13, 21 // The user can input a number n to find the rabbit sequence corresponding to this number // We only need to know the first two items (n-1, n-2) of N entered by the user to calculate the sequence value corresponding to n function fn(n) { if (n == 1 || n == 2) { return 1; } return fn(n - 1) + fn(n - 2); } console.log(fn(3)); //2 console.log(fn(8)); //21 </script>
Using recursion to traverse array data
<script> let data = [{ id: 1, name: "household electrical appliances", goods: [{ id: 11, name: "Refrigerator", }, { id: 12, name: "Washing machine", }, { id: 13, name: "Television", }, ], }, { id: 2, name: "Clothes & Accessories", }, ]; // We want to make a data object that can be returned by entering the id number // 1. Use forEach to traverse every object inside function getID(json, id) { let o = {}; json.forEach(function(item) { // console.log(item); // Two array elements //Object {ID: 1, name: "home appliances", goods: (3) [...]} // Object {ID: 2, name: "dress"} // Outer data if (item.id == id) { // console.log(item.name); o = item; } // Inner layer data else if (item.goods && item.goods.length > 0) { o = getID(item.goods, id); } }); return o; } console.log(getID(data, 1)); console.log(getID(data, 11)); </script>
Light copy and deep copy
- Shallow copy only copies one layer, and deeper object level can only copy references
- Deep copy copies multiple layers, and each level of data is copied
Shallow copy
<script> // Shallow copy copies only one layer, and deeper object level copies only references // Deep copy copies multiple layers, and each level of data is copied let obj = { id: 1, name: "andy", msg: { age: 18, }, }; let o = {}; // for (let k in obj) { // //K is the attribute name and obj[k] is the attribute value // o[k] = obj[k]; // } // console.log(o); // o.msg.age = 20; // console.log(obj); console.log("-----------"); Object.assign(o, obj); console.log(o); //Object { id: 1, name: "andy", msg: {...} } o.msg.age = 20; console.log(obj); </script>
Deep copy
<script> // Deep copy and shallow copy, each level of data will be copied let obj = { id:1, name:'andy', msg:{ age:18 }, color:['pink','red'] }; let o = {}; // Encapsulation function function deepCopy (newobj,lodobj){ for(let k in oldobj){ // Determine which data type our attribute value belongs to // 1. Get our property values let item = oldobj[k]; // 2. Determine whether the value is an array if(item instanceof Array){ newobj[k] = []; deepCopy(newobj[k],item) }else if(item instanceof Object){ // 3. Determine whether this value is an object newobj[k]={} deepCopy(newobj[k],item) }else{ // 4. It is a simple data type newobj[k] = item; } } } deepCopy(o,obj); console.log(o); let arr = []; console.log(arr instanceof Object); // true </script>
regular expression
See Introduction to js for detailed notes