Goal:

  • Understand object-oriented development ideas
  • Master JavaScript object-oriented development patterns
  • Learn to use regular expressions in JavaScript

review

Reintroducing JavaScript

What is the JavaScript

  • Parsing execution: Lightweight interpretation
  • Language features: dynamic, first-class Function
    • Functions are first-class citizens in JavaScript
  • Execution environment: Runs in the host environment, and the browser is the common JavaScript hosting environment – but JavaScript is also used in many non-browsers, such as Node.js
    • MDN-JavaScript

The composition of JavaScript

  • Ecma-script syntax specification
    • Variables, data types, type conversions, operators
    • Flow control statement: judge, loop statement
    • Array, function, scope, preparse
    • Differences between objects, properties, methods, simple types and complex types
    • Built-in objects: Math, Date, Array. Basic wrapper types: String, Number, Boolean
  • Web APIs
    • BOM
      • Onload page load event, Windows top-level event
      • The timer
      • The loaction, history
    • DOM
      • Page element, register event
      • Property manipulation, style manipulation
      • Node properties, node level
      • Dynamically creating elements
      • Event: how the event is registered, the three phases of the event, and the event object

What can JavaScript do

Atwood’s law:

Any application that can be written in JavaScript, will eventually be written in JavaScript.

Any application that can be written in JavaScript will eventually be written in JavaScript

How does a browser work

The Browser engine is used to query and manipulate the requested content, Rendering engine is responsible for parsing HTML, CSS, and Rendering engine. A JavaScript Interpreter, which executes JavaScript code UI Backend, is used to perform the following operations: Data Persistence, Data storage cookies, sessionStorage in HTML5Copy the code
  • Refer to the link
    • How browsers work
    • How Browsers Work: Behind the scenes of modern web browsers
    • JavaScript Patterns for 2017

JavaScript execution process

JavaScript runs in two phases

  • Preliminary analysis
    • Global parsing (all variables and functions are advanced; Functions and variables with the same name have higher precedence.
    • Function internal preparsing (all variables, functions, and parameters participate in preparsing)
      • function
      • parameter
      • Common variables
  • perform
    • The global scope is preparsed, and then the code in the global scope is executed. When a function call is encountered during the execution of the global code, the function is preparsed, and then the code in the function is executed

JavaScript object-oriented programming

Introduction to Object Orientation

What is an object

Everything is Object

  • There are two levels of understanding of what an object is.
    1. An object is an abstraction of a single thing
      • A book, a car, a person can all be objects, a database, a web page, a connection to a remote server can also be objects, using “properties” to record a specific kind of animal, using “methods” to represent certain animal behavior (running, hunting, resting).
    2. An object is a container that encapsulates properties and methods.
      • Properties are the state of the object, and methods are the behavior of the object (to accomplish something). For example, we can abstract an animal as an animal object, using “attributes” to record which animal it is, and “methods” to represent certain behaviors of the animal (running, hunting, resting, etc.).
      • In real development, an object is an abstract concept that can be understood as a data set or a set of features.
      • Ecma-262 defines an object as an unordered collection of attributes that can contain base values, objects, or functions
      • Strictly speaking, this is equivalent to saying that an object is a set of values in no particular order. Each property or method of an object has a name, and each name maps to a value
      • Tip: Each object is created based on a reference type, which can be either a built-in native type or a developer custom type.

What is object orientation

Object orientation is not new, it is just a high abstraction of procedural code to improve the efficiency and maintainability of code development

  • Object Oriented Programming, OOP for short, is a Programming development idea. It abstracts all kinds of complex relationships in the real world into objects, and then completes the simulation of the real world through the division of labor and cooperation between objects

  • In the idea of object-oriented program development, each object is a function center, with a clear division of labor, can complete the task of receiving information, processing data, sending information, etc. Therefore, object-oriented programming has the characteristics of flexibility, code reusable, highly modular, easy to maintain and develop. Large software projects that work better with multiple people than traditional procedural programming, which consists of a series of functions or instructions.

  • Object oriented and process oriented

    • Facing the process is to do everything personally, in every detail, in every aspect, step by step, orderly
    • Object orientation is taking an object and telling it what to do
    • Object orientation is turning the actor into the leader
    • Object orientation is not a process – oriented replacement, but a process – oriented encapsulation
  • Object-oriented features

    • encapsulation
    • inheritance
    • Polymorphism: Abstraction

Reference links:

  • Wikipedia – Object-oriented programming
  • Zhihu: How to explain in one sentence what is object oriented thinking?
  • Zhihu: What is the idea of object-oriented programming?

Program in the object – oriented basic embodiment

In JavaScript, all data types can be treated as objects, although you can also customize objects. Suppose we want to process a student’s grade table. To represent a student’s grade, a process-oriented program can be represented by an object:

var std1 = {name: 'zhanSan'.score:80 }
var std2 = {name: 'Bob'.score:90}
Copy the code

Processing student grades can be done by functions, such as printing student grades

function(){
console.log('name' + student.name + ' '+ 'results'+student.score)}
Copy the code

In object-oriented programming, the first thing we want to think about is not the execution of the program but the student data type should be treated as an object with properties like name and Score.

If you want to print a student’s score, you must first create an object corresponding to the student, and then send a printScore message to the object to print out its own data.

Abstract Data Behavior Template (Class)

function Student(name, score){
this.name = name;
this.score = score;
this.printScore = function(){
console.log('name' +this.name + ' ' + 'results' + this.score); }}Copy the code

Create a concrete Instance object from a template:

var std1 = new Student('Michael'.98)
var std2 = new Student('Bob'.81)
Copy the code

Instance objects have their own specific capabilities

std1.printScore() // => Name: Michael Grade: 98
std2.printScore() // => Name: Bob grade 81
Copy the code

The idea of object-oriented design comes from nature, where the concepts of classes and instances are natural. Class is an abstract concept. For example, Class — Student is defined to refer to the concept of a Student, while Instance is a concrete Student. For example, Michael and Bob are two concrete students.

Therefore, the idea of object-oriented design is:

  • Abstract the Class(constructor)
  • Create Instance based on Class(constructor)
  • Command the result of Instance

Object-oriented is also more abstract than functions, because a Class contains both data and methods to manipulate it.

Create an object

A simple way

We can create it with new Object()

var person = new Object()
person.name = 'Jack'
person.age = 18

person.sayName = function () {
  console.log(this.name)
}
Copy the code

A simplified version of new Object()

var person = {
  name: 'Jack'.age: 18.sayName: function () {
    console.log(this.name)
  }
}
Copy the code

Generate two persion instance objects

var person1 = {
  name: 'Jack'.age: 18.sayName: function () {
    console.log(this.name)
  }
}

var person2 = {
  name: 'Mike'.age: 16.sayName: function () {
    console.log(this.name)
  }
}
Copy the code

Easy way to enter: factory function

We can write a function to solve the code duplication problem

function createPerson (name, age) {
  return {
    name: name,
    age: age,
    sayName: function () {
      console.log(this.name)
    }
  }
}
Copy the code

Generate instance objects

var p1 = createPerson('Jack'.18)
var p2 = createPerson('Mike'.18)
Copy the code

The constructor

Content guidance:

  • Constructor syntax
  • Analysis constructor
  • The relationship of constructors to instances
    • The constructor property of the instance
    • The instanceof operator
  • The difference between a normal function call and a constructor call
  • The return value of the constructor
  • Constructor problem

More elegant factory functions: constructors

function Persion (name ,age){
this.name = name
this.age = age
this.sayName = function(){

console.log(this.name)}}
var p1 = new Persion('jack'18.)
p1.sayName() //jack

var p2 = new Person('Mike'.23)
p2.sayName() // => Mike
Copy the code

Parsing the execution of the constructor code

In the above example, the Person() function replaces the createPerson() function, but the implementation is the same. Why is that?

We notice the following differences between the code in Person() and createPerson() :

  • Create object not displayed
  • Assigning properties and methods directly tothisobject
  • There is noreturnstatements
  • The function name is uppercasePerson

To create a Person instance, you must use the new operator. Calling the constructor in this way goes through four steps:

  1. Create a new object
  2. Assign the constructor’s scope to the new object (so this refers to the new object)
  3. Execute the code in the constructor
  4. Return a new object

Here is the specific pseudocode:

function Person (name, age) {
  When Person() is called with the new operator, an object is actually created first
  // var instance = {}
  // Then make the inner this point to the instance object
  // this = instance
  // All subsequent operations on this actually operate on instance

  this.name = name
  this.age = age
  this.sayName = function () {
    console.log(this.name)
  }

  // This is returned at the end of the function, which is instance
  // return this
}
Copy the code

The relationship between constructors and instance objects

The advantage of using constructors is not only the simplicity of the code, but also the fact that we can identify the specific type of the object. Within each instance object there is also a constructor property that points to the constructor that created the instance:

console.log(p1.constructor === Person) // => true
console.log(p2.constructor === Person) // => true
console.log(p1.constructor === p2.constructor) // => true
Copy the code

The constructor property of an object is originally used to identify the type of the object, but it is more reliable to use the instanceof operator if you want to detect the type of the object:

console.log(p1 instanceof Person) // => true
console.log(p2 instanceof Person) // => true
Copy the code

Conclusion:

  • Constructors are abstract templates abstracted from concrete objects
  • An instance object is a concrete instance object derived from an abstract constructor template
  • Each instance object has oneconstructorProperty pointing to the constructor that created the instance
    • Note:constructorProperties of instances are not exact, as we’ll see later in the prototype
  • It can be instantiatedconstructorAttribute determines the relationship between the instance and the constructor
    • Note: This method is not rigorous, recommended useinstanceofOperator, and we’ll see why later in the prototype, okay

Constructor problem

The biggest benefit of using constructors is that they make it easier to create objects, but there is a problem of wasting memory:

function Person (name, age) {
  this.name = name
  this.age = age
  this.type = 'human'
  this.sayHello = function () {
    console.log('hello ' + this.name)
  }
}

var p1 = new Person('Tom'.18)
var p2 = new Person('Jack'.16)
Copy the code

In this example, while on the surface there seems to be nothing wrong, there is a big downside to doing so. For each instance object, type and sayHello are the same, and each instance must consume more memory for duplicate content. If there are many instance objects, there will be a huge waste of memory.

console.log(p1.sayHello === p2.sayHello) // => false
Copy the code

To solve this problem, we can define functions that need to be shared outside the constructor:

function sayHello = function () {
  console.log('hello ' + this.name)}function Person (name, age) {
  this.name = name
  this.age = age
  this.type = 'human'
  this.sayHello = sayHello
}

var p1 = new Person('Top'.18)
var p2 = new Person('Jack'.16)

console.log(p1.sayHello === p2.sayHello) / / = >true
Copy the code

This is fine, but if you have multiple functions that need to be shared, you can cause global namespace conflicts.

You might think of the problem of putting multiple functions into an object to avoid global namespace collisions:

var fns = {
  sayHello: function () {
    console.log('hello ' + this.name)
  },
  sayAge: function () {
    console.log(this.age)
  }
}

function Person (name, age) {
  this.name = name
  this.age = age
  this.type = 'human'
  this.sayHello = fns.sayHello
  this.sayAge = fns.sayAge
}

var p1 = new Person('lpz'.18)
var p2 = new Person('Jack'.16)

console.log(p1.sayHello === p2.sayHello) // => true
console.log(p1.sayAge === p2.sayAge) // => true
Copy the code

So far, we have basically solved the constructor’s memory waste problem in our own way. But the code still looks so out of place, is there a better way?

summary

  • Constructor syntax
  • Analysis constructor
  • The relationship between constructors and instance objects
    • The constructor property of the instance
    • The instanceof operator
  • Constructor problem

The prototype

Content guidance:

  • Use the Prototype object to solve the constructor problem
  • Analyze the relationships among constructors, Prototype objects, and instance objects
  • Attribute member search principle: prototype chain
  • The instance object reads and writes members of the prototype object
  • Shorthand for a prototype object
  • A prototype of a native object
    • Object
    • Array
    • String
    • .
  • Problems with prototype objects
  • Suggestions for using constructed functions and prototype objects

A better solution:prototype

JavaScript states that each constructor has a Prototype property that points to another object. All properties and methods of this object are owned by the constructor.

This means that we can define properties and methods that all object instances need to share directly on the Prototype object.

function Person (name, age) {
  this.name = name
  this.age = age
}

console.log(Person.prototype)

Person.prototype.type = 'human'

Person.prototype.sayName = function () {
  console.log(this.name)
}

var p1 = new Person(...)
var p2 = new Person(...)

console.log(p1.sayName === p2.sayName) // => true
Copy the code

The sayName() method and the Type attribute of all instances refer to the same memory address, pointing to the Prototype object, thus making the operation more efficient.

The relationship between constructors, instances, and stereotypes

Any function has oneprototypeProperty, which is an object.

function F () {}
console.log(F.prototype) // => object

F.prototype.sayHi = function () {
  console.log('hi! ')}Copy the code

The prototype object of a constructor default has a constructor attribute pointing to the function of the Prototype object.

console.log(F.prototype.constructor === F) // => true
Copy the code

Constructor instance objects contain a pointer to the constructor’s prototype object __proto__.

var instance = new F()
console.log(instance.__proto__ === F.prototype) // => true
Copy the code

__proto__ is a nonstandard attribute.

Instance objects have direct access to prototype object members.

instance.sayHi() // => hi!
Copy the code

Conclusion:

  • Any function has oneprototypeProperty, which is an object
  • constructionalprototypeObjects have one by defaultconstructorProperty, pointing toprototypeObject function
  • An instance object derived from a constructor contains an internal reference to the constructorprototypeObject pointer__proto__
  • All instances inherit directly or indirectly from members of the prototype object

The search principle for attribute members: prototype chain

Now that we understand the construction-instance-stereotype relationship, let’s explain why instance objects can access members in stereotype objects.

Every time the code reads an attribute of an object, a search is performed for the attribute with the given name

  • The search starts with the object instance itself
  • If an attribute with the given name is found in the instance, the value of that attribute is returned
  • If not, search continues for the prototype object to which the pointer points, looking for the property with the given name in the prototype object
  • If the property is found in the stereotype object, the value of the property is returned

That is, when we call person1.sayname (), we perform two searches:

  • First, the parser asks, “Does instance person1 have the sayName attribute?” A: “No.
  • “It then searches again and asks,” Does the person1 prototype have the sayName attribute?” A: “Yes.
  • “It then reads the function stored in the prototype object.
  • When we call person2.sayname (), the same search process is repeated, with the same results.

This is the rationale for multiple object instances sharing the properties and methods saved by the stereotype.

Conclusion:

  • Look for yourself first, and return when you find it
  • If you can’t find it on your own body, you’ll look up the prototype chain and return if you find it
  • If not found all the way to the end of the prototype chain, returnundefined

Instance objects read and write prototype object members

Read:

  • Look for yourself first, and return when you find it
  • If you can’t find it on your own body, you’ll look up the prototype chain and return if you find it
  • If not found all the way to the end of the prototype chain, returnundefined

Value type members write to (instance objects. Value type member = xx) :

  • When an instance expects to override a common data member in a stereotype object, it actually adds that member to itself
  • That is, this behavior actually blocks access to the prototype object members

Reference type member writes (instance object. Reference type member = xx) :

  • Same as above

Complex type modification (instance object. Member. Xx = xx) :

  • It will also look for the member on its own body first, and if it is found on its own body, it will directly modify
  • If you can’t find it on your own, continue to look along the prototype chain, and if you find it, modify it
  • If the member is not found until the end of the prototype chain, an error is reported (Undefined. Xx = xx)

Simpler prototype syntax

In order to reduce unnecessary input, it is more common to rewrite the entire prototype object with an object literal containing all properties and methods:

function Person (name, age) {
  this.name = name
  this.age = age
}

Person.prototype = {
  type: 'human'.sayHello: function () {
    console.log('my name is' + this.name + 'I am this year' + this.age + 'old')}}Copy the code

In this example, we reset Person.Prototype to a new object. This has the advantage of being easy to add members to Person.prototype, but it also introduces the problem of the prototype object missing its constructor member.

So, to keep constructor pointing correctly, we recommend writing:

function Person (name, age) {
  this.name = name
  this.age = age
}

Person.prototype = {
  constructor: Person, // => Manually point constructor to the correct constructor
  type: 'human'.sayHello: function () {
    console.log('my name is' + this.name + 'I am this year' + this.age + 'old')}}Copy the code

A prototype of a native object

All functions have a Prototype property object.

  • Object.prototype
  • Function.prototype
  • Array.prototype
  • String.prototype
  • Number.prototype
  • Date.prototype
  • .

Exercise: Extend prototype methods for array objects and string objects.

Suggestions for using prototype objects

  • Private members (usually non-function members) are put into constructors
  • Shared members (typically functions) are placed in the prototype object
  • If I reset itprototypeRemember to correctconstructorThe point to

inheritance

What is inheritance

  • Inheritance in real life
  • Inheritance in program

Attribute inheritance of constructors: borrow constructors

function Person (name, age) {
  this.type = 'human'
  this.name = name
  this.age = age
}

function Student (name, age) {
  // Borrow constructor to inherit attribute members
  Person.call(this, name, age)
}

var s1 = Student('Joe'.18)
console.log(s1.type, s1.name, s1.age) // => human
Copy the code

Prototype method Inheritance of constructors: Copy Inheritance (for-in)

function Person (name, age) {
  this.type = 'human'
  this.name = name
  this.age = age
}

Person.prototype.sayName = function () {
  console.log('hello ' + this.name)
}

function Student (name, age) {
  Person.call(this, name, age)
}

// Prototype object copy inherits prototype object members
for(var key in Person.prototype) {
  Student.prototype[key] = Person.prototype[key]
}

var s1 = Student('Joe'.18)

s1.sayName() // => Hello Zhang SAN
Copy the code

Another type of inheritance: archetypal inheritance

function Person (name, age) {
  this.type = 'human'
  this.name = name
  this.age = age
}

Person.prototype.sayName = function () {
  console.log('hello ' + this.name)
}

function Student (name, age) {
  Person.call(this, name, age)
}

// Implement inheritance using the properties of prototypes
Student.prototype = new Person()

var s1 = Student('Joe'.18)

console.log(s1.type) // => human

s1.sayName() // => Hello Zhang SAN
Copy the code

Function is advanced

The way a function is defined

  • Function declaration
  • Functional expression
  • new Function

Function declaration

function foo () {}Copy the code

Functional expression

var foo = function () {}Copy the code

The difference between function declarations and function expressions

  • Function declarations must have names
  • Function declarations are promoted, created in the pre-parsing phase, and can be called before and after the declaration
  • Function expressions are similar to variable assignments
  • Function expressions can have no names, such as anonymous functions
  • Function expressions have no variable promotion, are created at execution time and can only be called after the expression is executed

Here is an example of defining a function based on a condition:

if (true) {
  function f () {
    console.log(1)}}else {
  function f () {
    console.log(2)}}Copy the code

The above code execution results are inconsistent in different browsers.

But we can use functional expressions to solve the above problem:

var f

if (true) {
  f = function () {
    console.log(1)}}else {
  f = function () {
    console.log(2)}}Copy the code

How a function is called

  • Common function
  • The constructor
  • Object methods

Within the functionthisDifferent scenarios to point to

How the function is called determines which this refers to differently:

Call way Nonstrict mode note
Ordinary function calls window In strict mode, undefined
Constructor call Instance objects This is also an instance object in the prototype method
Object method call The object to which the method belongs The object next to it
Event binding method Bind event object
Timer function window

This is the basic arrangement of what this points to inside the function, and you’ll be familiar with it if you write a lot of code.

Functions are objects

  • All functions areFunctionAn instance of the

Call, apply, bind

Now that we know about the different scenarios that this refers to, we know that there are cases where we need to do something special to use this reference in a particular context. For example, we often back up this reference outside the timer. Then use a reference to the external this inside the timer function. However, in fact, our JavaScript provides some function methods to help us deal more elegantly with this pointing problems inside functions. These are the call, apply, and bind methods that we’ll look at next.

call

The call() method calls a function with a specified this value and separately supplied arguments (a list of arguments).

Note: This method is similar to ‘apply()’ except that ‘call()’ takes a list of arguments, whereas’ apply() ‘takes an array of arguments.

Grammar:

fun.call(thisArg[, arg1[, arg2[, ...]]])
Copy the code

Parameters:

  • thisArg

    • The this value specified when fun is run
    • If null or undefined the internal this points to the window
  • arg1, arg2, ...

    • Specifies the argument list

apply

The apply() method calls a function with a specified this value and arguments supplied as an array (or array-like object).

Note: This method works like ‘call()’ except that ‘call()’ takes a list of arguments, while ‘apply()’ takes an array of arguments.

Grammar:

fun.apply(thisArg, [argsArray])
Copy the code

Parameters:

  • thisArg
  • argsArray

Apply () is very similar to call(), except for the way arguments are provided. Apply () uses an array of arguments rather than a list of arguments. Such as:

fun.apply(this['eat'.'bananas'])
Copy the code

bind

The bind() function creates a new function (called a binding function) that has the same function body (the call attribute built into the ECMAScript 5 specification) as the called function (the target function of the binding function). This is bound to the first argument of bind() when the target function is called, which cannot be overridden. When a binding function is called, bind() also accepts the default arguments supplied to the original function. A binding function can also use the new operator to create objects: this behavior is like treating the original function as a constructor. The supplied this value is ignored, and the arguments to the call are supplied to the mock function.

Grammar:

fun.bind(thisArg[, arg1[, arg2[, ...]]])
Copy the code

Parameters:

  • thisArg

    • This parameter is referred to as this when the binding function is called. This parameter is invalid when a binding function is called using the new operator.
  • arg1, arg2, …

    • When the binding function is called, these arguments are passed to the bound method before the arguments.

The return value:

Returns a copy of the original function modified with the specified this value and initialization arguments.

Example 1:

this.x = 9; 
var module = {
  x: 81.getX: function() { return this.x; }};module.getX(); / / back to 81

var retrieveX = module.getX;
retrieveX(); // Returns 9, in which case "this" refers to the global scope

// Create a new function that binds "this" to the Module object
// Beginners can be confused by the global x variable and the x attribute in the module
var boundGetX = retrieveX.bind(module);
boundGetX(); / / back to 81
Copy the code

Example 2:

function LateBloomer() {
  this.petalCount = Math.ceil(Math.random() * 12) + 1;
}

// Declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
  window.setTimeout(this.declare.bind(this), 1000);
};

LateBloomer.prototype.declare = function() {
  console.log('I am a beautiful flower with ' +
    this.petalCount + ' petals! ');
};

var flower = new LateBloomer();
flower.bloom();  // After one second, call the 'declare' method
Copy the code

summary

  • Call and Apply feature the same

    • Both are used to call functions, and immediately
    • However, you can specify the inside of the function with the first argument at the same time that the function is calledthisThe point to
    • When a call is called, the arguments must be passed as a list of arguments, separated by commas
    • When apply calls, the parameters must be an array, and when executed, the elements inside the array are taken out one by one, passing them along with the corresponding parameters
    • If the first argument is specifiednullorundefinedThe inner this points to the window
  • bind

    • Can be used to specify the pointer to this inside, and then generate a new function that changes the pointer to this
    • The biggest difference between call and apply is that bind does not call
    • Bind supports passing parameters in a special way: there are two places to pass parameters
        1. Pass it as a list of arguments along with bind
        1. When called, it is passed as a list of arguments
      • So which one is the argument that you pass when you bind or the argument that you pass when you call
      • The two are merged: the arguments passed by bind and the arguments passed by call are merged and passed inside the function

Other members of the function

  • arguments
    • Collection of arguments
  • caller
    • The caller of a function
  • length
    • Number of parameters
  • name
    • Function name
function fn(x, y, z) {
  console.log(fn.length) // => Number of parameters
  console.log(arguments) // A collection of pseudo-array arguments
  console.log(arguments.callee === fn) // The function itself
  console.log(fn.caller) // The caller of the function
  console.log(fn.name) // => The function name
}

function f() {
  fn(10.20.30)
}

f()
Copy the code

Higher-order functions

  • Functions can be arguments
  • A function can be a return value

As a parameter

function eat (callback) {
  setTimeout(function () {
    console.log('Eaten up')
    callback()
  }, 1000)
}

eat(function () {
  console.log('Go and sing')})Copy the code

As a return value

function genFun (type) {
  return function (obj) {
    return Object.prototype.toString.call(obj) === type
  }
}

var isArray = genFun('[object Array]')
var isObject = genFun('[object Object]')

console.log(isArray([])) // => true
console.log(isArray({})) // => true
Copy the code

A function closure

function fn () {
  var count = 0
  return {
    getCount: function () {
      console.log(count)
    },
    setCount: function () {
      count++
    }
  }
}

var fns = fn()

fns.getCount() / / = > 0
fns.setCount()
fns.getCount() / / = > 1
Copy the code

Scope, scope chain, pre-resolution

  • Global scope
  • Function scope
  • There is no block-level scope
{
  var foo = 'bar'
}

console.log(foo)

if (true) {
  var a = 123
}
console.log(a)
Copy the code

Sample code for scope chain:

var a = 10

function fn () {
  var b = 20

  function fn1 () {
    var c = 30
    console.log(a + b + c)
  }

  function fn2 () {
    var d = 40
    console.log(c + d)
  }

  fn1()
  fn2()
}
Copy the code
  • Inner scopes can access outer scopes, but not vice versa

What is a closure

A closure is a function that can read variables inside other functions. In Javascript, only a child function inside a function can read local variables, so a closure can be simply understood as “a function defined inside a function.” So, in essence, a closure is a bridge between the inside and outside of a function.

Closures are useful for:

  • Function members can be read outside a function
  • Keeps function members alive in memory at all times

Some examples of closures

Example 1:

var arr = [10.20.30]
for(var i = 0; i < arr.length; i++) {
  arr[i] = function () {
    console.log(i)
  }
}
Copy the code

Example 2:

console.log(111)

for(var i = 0; i < 3; i++) {
  setTimeout(function () {
    console.log(i)
  }, 0)}console.log(222)
Copy the code

Example 3: Voting

Example 4: Determine the type

Example 5: Sandbox mode

Thinking about closures

Question 1:

var name = "The Window";
var object = {
  name: "My Object".getNameFunc: function () {
    return function () {
      return this.name; }; }};console.log(object.getNameFunc()())
Copy the code

Question 2:

var name = "The Window";varobject = {name: "My Object".getNameFunc: function () {
    var that = this;
    return function () {
      returnthat.name; }; }};console.log(object.getNameFunc()())
Copy the code

summary

Function recursive

Recursive execution model

function fn1 () {
  console.log(111)
  fn2()
  console.log('fn1')}function fn2 () {
  console.log(222)
  fn3()
  console.log('fn2')}function fn3 () {
  console.log(333)
  fn4()
  console.log('fn3')}function fn4 () {
  console.log(444)
  console.log('fn4')
}

fn1()
Copy the code

For example: a recursive function that computes factorial

function factorial (num) {
  if (num <= 1) {
    return 1
  } else {
    return num * factorial(num - 1)}}Copy the code

Recursive application scenarios

  • Deep copy
  • The menu tree
  • Traverse the DOM tree

Regular expression

  • Understand the basic regular expression syntax
  • A regular object that can use JavaScript

Introduction to regular Expressions

What is a regular expression

Regular expressions: Expressions used to match regular rules. Regular expressions began as scientists’ early study of how the human nervous system works and are now widely used in programming languages. Regular tables are often used to retrieve and replace text that conforms to a pattern (rule). A regular expression is a logical formula used to manipulate strings. It uses predefined characters and the combination of these characters to form a “regular string”. The “regular string” is used to filter strings.

Function of regular expressions

  1. Whether a given string conforms to the regular expression’s filtering logic (match)
  2. We can use regular expressions to get the specific part of the string we want (extract)
  3. Strong string substitution capability (substitution)

Features of regular expressions

  1. It’s flexible, logical, and functional
  2. Complex control of strings can be achieved quickly and in a very simple manner
  3. For people who are new to it, it’s kind of obscure

Regular expression testing

  • Online test re
  • Regular expressions are used in the tool
    • sublime/vscode/word
    • Show how to replace all numbers

Composition of a regular expression

  • Normal character
  • Special characters (metacharacters) : characters that have special meaning in the regular expression

Example demonstration:

  • \dMatch the Numbers
  • ab\dMatches AB1 and AB2

Yuan string

Use the test tool to demonstrate the following metacharacters

Common meta-string

metacharacters instructions
\d Match the Numbers
\D Matches any non-numeric character
\w Matches letters or numbers or underscores
\W Matches anything other than letters, numbers, and underscores
\s Matches any whitespace character
\S Matches any character that is not a whitespace character
. Matches any single character except newline
^ The text that matches the beginning of the line (with whom to start)
$ The text that matches the end of the line (where it ends)

qualifiers

qualifiers instructions
* Repeat zero or more times
+ Repeat once or more
? Repeat zero times or once
{n} Repeated n times
{n,} Repeat n times or more
{n,m} Repeat n to m times

other

Enclosed in brackets [] string, means to match any of these characters, the meaning of is equal to or [^] match in addition to the content within the brackets \ escape characters | or, choose one of the two. Note | left and right sides can be divided into two parts, and no matter how long the left and right sides more random () choose one of the amount directly from two, grouping eg: gr (a) | e y matching gray and grey [\ u4e00 \ u9fa5] - match the Chinese charactersCopy the code

case

Verification Mobile phone number:

^\d{11} $Copy the code

Verify zip code:

^\d{6} $Copy the code

Verification date: May 1st, 2012

^\d{4}-\d{1.2}-\d{1.2} $Copy the code

Verification email [email protected]:

^\w+@\w+\.\w+$
Copy the code

Verify the IP address 192.168.1.10

^\d{1.3}\(.\d{1.3{})3} $Copy the code

Regular expressions are used in JavaScript

Creating a regular object

Method 1:

var reg = new Regex('\d'.'i');
var reg = new Regex('\d'.'gi');
Copy the code

Method 2:

var reg = /\d/i;
var reg = /\d/gi;
Copy the code

parameter

mark instructions
i Ignore case
g The global matching
gi Global match + ignores case

Regular match

// Match the date
var dateStr = '2015-10-10';
var reg = / ^ \ d {4} \ d {1, 2} - \ d {1, 2} $/
console.log(reg.test(dateStr));
Copy the code

Regular extraction

// 1
var str = "Zhang SAN: 1000, Li Si: 5000, Wang Wu: 8000.";
var array = str.match(/\d+/g);
console.log(array);

// 2. Extract the email address
var str = 286669312 @qq.com 2 "123123 @xx.com, [email protected], emailenglishenglish.englishtown.com [email protected]...";
var array = str.match(/\w+@\w+\.\w+(\.\w+)? /g);
console.log(array);

// 3. Group extraction
// 3. The year part of the extraction date is 2015-5-10
var dateStr = '2016-1-5';
Regex.$1 $2 $3.... In order to get
var reg = / (\ d {4}) - \ d {1, 2} - \ d {1, 2} /;
if (reg.test(dateStr)) {
  console.log(RegExp. $1); }// 4. Extract each part of the message
var reg = /(\w+)@(\w+)\.(\w+)(\.\w+)? /;
var str = "[email protected]";
if (reg.test(str)) {
  console.log(RegExp. $1);console.log(RegExp. $2);console.log(RegExp. $3); }Copy the code

Regular replacement

// 1. Replace all blanks
var str = " 123AD asadf asadfasf adf ";
str = str.replace(/\s/g."xx");
console.log(str);

/ / 2. Replace all, |.
var str = "abc,efg,123,abc,123,a";
str = str.replace(/ g /, |.".");
console.log(str);
Copy the code

Example: Form validation

QQ number:<input type="text" id="txtQQ"><span></span><br>Email address:<input type="text" id="txtEMail"><span></span><br>Mobile phone:<input type="text" id="txtPhone"><span></span><br>Birthday:<input type="text" id="txtBirthday"><span></span><br>Name:<input type="text" id="txtName"><span></span><br>
Copy the code
// Get the text box
var txtQQ = document.getElementById("txtQQ");
var txtEMail = document.getElementById("txtEMail");
var txtPhone = document.getElementById("txtPhone");
var txtBirthday = document.getElementById("txtBirthday");
var txtName = document.getElementById("txtName");

//
txtQQ.onblur = function () {
  // Get the span corresponding to the current text box
  var span = this.nextElementSibling;
  var reg = / ^ \ d {5, 12} $/;
  // Check whether the validation was successful
  if(! reg.test(this.value) ){
    // Verification failed
    span.innerText = "Please enter the correct QQ number";
    span.style.color = "red";
  }else{
    // Verification succeeded
    span.innerText = "";
    span.style.color = ""; }};//txtEMail
txtEMail.onblur = function () {
  // Get the span corresponding to the current text box
  var span = this.nextElementSibling;
  var reg = /^\w+@\w+\.\w+(\.\w+)? $/;
  // Check whether the validation was successful
  if(! reg.test(this.value) ){
    // Verification failed
    span.innerText = "Please enter the correct EMail address";
    span.style.color = "red";
  }else{
    // Verification succeeded
    span.innerText = "";
    span.style.color = ""; }};Copy the code

Form validation section, encapsulated as a function:

var regBirthday = / ^ \ d {4} \ d {1, 2} - \ d {1, 2} $/;
addCheck(txtBirthday, regBirthday, "Please enter the correct date of birth");
// Add validation to the text box
function addCheck(element, reg, tip) {
  element.onblur = function () {
    // Get the span corresponding to the current text box
    var span = this.nextElementSibling;
    // Check whether the validation was successful
    if(! reg.test(this.value) ){
      // Verification failed
      span.innerText = tip;
      span.style.color = "red";
    }else{
      // Verification succeeded
      span.innerText = "";
      span.style.color = ""; }}; }Copy the code

Validate forms by adding custom validation attributes to elements:

<form id="frm">QQ number:<input type="text" name="txtQQ" data-rule="qq"><span></span><br>Email address:<input type="text" name="txtEMail" data-rule="email"><span></span><br>Mobile phone:<input type="text" name="txtPhone" data-rule="phone"><span></span><br>Birthday:<input type="text" name="txtBirthday" data-rule="date"><span></span><br>Name:<input type="text" name="txtName" data-rule="cn"><span></span><br>
</form>
Copy the code
// All validation rules
var rules = [
  {
    name: 'qq'.reg: / ^ \ d {5, 12} $/,
    tip: "Please enter the correct QQ"
  },
  {
    name: 'email'.reg: /^\w+@\w+\.\w+(\.\w+)? $/,
    tip: "Please enter the correct email address"
  },
  {
    name: 'phone'.reg: /^\d{11}$/,
    tip: "Please enter the correct mobile phone number."
  },
  {
    name: 'date'.reg: / ^ \ d {4} \ d {1, 2} - \ d {1, 2} $/,
    tip: "Please enter the correct date of birth"
  },
  {
    name: 'cn'.reg: / ^ [\ u4e00 - \ u9fa5] {2, 4} $/,
    tip: "Please enter the correct name"
  }];

addCheck('frm');


// Add validation to the text box
function addCheck(formId) {
  var i = 0,
      len = 0,
      frm =document.getElementById(formId);
  len = frm.children.length;
  for (; i < len; i++) {
    var element = frm.children[i];
    // Add validation for elements with a name attribute in the form element
    if (element.name) {
      element.onblur = function () {
        // Use the dataset to retrieve the data- custom attribute value
        var ruleName = this.dataset.rule;
        var rule =getRuleByRuleName(rules, ruleName);

        var span = this.nextElementSibling;
        // Check whether the validation was successful
        if(! rule.reg.test(this.value) ){
          // Verification failed
          span.innerText = rule.tip;
          span.style.color = "red";
        }else{
          // Verification succeeded
          span.innerText = "";
          span.style.color = "";
        }
      }
    }
  }
}

// Get the rule object based on the rule name
function getRuleByRuleName(rules, ruleName) {
  var i = 0,
      len = rules.length;
  var rule = null;
  for (; i < len; i++) {
    if (rules[i].name == ruleName) {
      rule = rules[i];
      break; }}return rule;
}
Copy the code

The appendix

A code specification

Code style.

  • JavaScript Standard Style
  • Airbnb JavaScript Style Guide() {

Check tools

  • JSLint
  • JSHint
  • ESLint

B Chrome developer tools

C Documents related tools

  • Electronic document making tool: Docute
  • Flowchart tool: DiagramDesigner