“JavaScript Advanced Programming (3rd edition)” study notes

Related content:

Learning JavaScript (3)- Talk about prototype chains – 1. Variables

Learning JavaScript (3)- Talk about prototype chains – 2. Objects and prototypes

Learning JavaScript (3)- Talk about prototype chains – 3. Prototype chains and inheritance


Keywords: JavaScript variables, primitive types, reference types, Instanceof, Typeof, Object, Array, function

Learning ideas: To learn the prototype chain, we need to first understand the knowledge of variables, then learn the creation of objects, object prototypes, and finally the relationship between inheritance

1. Basic concepts of variables

Basic types of Reference types
concept Simple data segment An object that may consist of multiple values
The data type Undefined, Null, Boolean, Number, String Object
The assignment var name = 13 var name = new Object()

name.age = 13
Copy the reference Var num2 = num1

Num1 and NUM2 are independent of each other. Changing NUM1 does not affect NUM2
var obj2 = obj1

Changing obj1 affects obj2, which actually references the same object

2. Basic types

The data type English expression TypeOf returns the result
undefined undefined “undefined”
Boolean value Boolean “boolean”
string String “string”
The numerical Number “number”
Null Null “object”
function function “function”

3. Reference types

Common reference types: Object, Array, Date, RegExp, Function

Custom reference types can also be created using custom constructors, but custom types are essentially inherited from the default reference type

3.1 Checking the reference type – Instanceof

Typeof does not detect specific reference types (object, array, date…..)

For example, null and object typeof values are both Object and cannot be distinguished

  1. Determine the type – instanceof – returns true/false
/ / instanceof sample
var o = new Object()

alert(o instanceof Array)
alert(o instanceof Constructor)
alert(o instanceof RegExp)  
Copy the code
  1. For some types, you can also use your own type detection methods
// Array type - check method: array.isarray ()
alert(Array.isArray(colors)) // true
Copy the code

3.2 the Object type

/ / create the Object
// 1. New an Object, use the Object constructor, and add attributes
var person = new Object()
person.name = "Cindy"
person.age = 27

// 2. Object literals - Create them directly as JSON objects
var person = {
  name: "Cindy".age: 27
}
// Note: Same as new Object() when Object literals are created without property values
var person = {} // Same as new Object()

// Object access methods
person.name     // Output: Cindy
person["name"]  // Output: Cindy - Square brackets pass in string methods to facilitate passing in variables to dynamically get different values in the object
Copy the code

3.3 Array type

// Create a method
// 1. new an Array object, using the Array constructor
var colors = new Array(a)var colors = new Array(20)
var colors = new Array('red'.'blue'.'yellow')
var colors = Array("Gray") // You can do without new

// 2. Array literals
var colors = []
var colors = ['red'.'blue'.'yellow']


// Object access methods
// 1. The Array object contains length
alert(colors.length) / / 3

// 2. Array objects can be referenced with subscripts
colors[0] = "gray"
alert(colors[0]) // Output: "gray"
Copy the code

3.4 the Date type

  • Recommend Momentjs library for time and date conversion
// Create a date object that automatically retrieves the current date
var now = new Date(a)// Receive date representation string, converted to the corresponding date in milliseconds
Date.parse("6/13/2008")

// Format the date
toDateString()       // Displays the day of the week, month, day, and year in implementation-specific format
toTimeString()       // Display hours, minutes, seconds, and time zone in implementation-specific format
toLocaleDateString() // Displays the day of the week, month, day, and year in locale-specific format
toLocaleTimeString() // Display hours, minutes, and seconds in locale-specific formats
toUTCString()        // Displays the UTC date in implementation-specific format
Copy the code

3.5 the RegExp type

Create regular expressions using Perl-like syntax

var expression = / pattern / flag
Copy the code

Flag – Table name regular expression behavior:

  1. G – Global mode, applied to all strings
  2. I – is case insensitive
  3. M – Multi-line mode. At the end of a line of text, the search continues to see if there is an item matching the pattern in the next line

3.6 the Function type

3.6.1 Functions declare methods

The parser reads the function declaration first and adds it to the execution environment, so the code can be written before the function declaration when called

// Function declaration - syntax:
function funName (arg0, arg1, arg2) {
  / / the function body
}

// Function declaration promotion - The calling statement can precede the function declaration because the code reads the function declaration before execution
sayHi()
function sayHi() {
  alert('Hi')}Copy the code

3.6.2 Function expression method

Function declarations cannot be promoted by the parser and added to the execution environment first, so they must be written after expressions when called

// Function expression - syntax - Assigns an anonymous function to a variable
// Anonymous functions: function is not named
var funName = function (arg0, arg1, arg2) {
  / / the function body
}

// Function expressions cannot be promoted with function declarations. Calls are made after expressions
var sayHi = function () { 
  alert('Hi')
}
sayHi()
Copy the code

3.6.3 Issues needing attention about function:

  1. Function pointer reference
// Pointer reference
var sum2 = sum1 Sum1 and sum2 both refer to the same function content
Copy the code
  1. Function is not overloaded
// function is not overloaded with Pointers
var add1 = function (num) { return num + 100 }
add1 = function(num) { return num + 200 } // When the second function is created, it actually overwrites the first reference, so there is no overloading
Copy the code

3.6.4 function的传参 – arguments

3.6.4.1 understanding the arguments

  1. You don’t have to declare arguments to function; you can use the arguments object instead of explicitly using named arguments
function sayHi() {
  alert("Hello " + arguments[0] + ', ' + arguments[1])}Copy the code
  1. Arguments objects are similar to Array calls, but are not instances of Array
  2. The number of arguments passed in a function need not be the same as the number of declared arguments, because inside a function values are retrieved as arrays
function sayHi (name1, name2) {
  alert("Hello " + name1 + ', ' + name2)
}

sayHi('Alice')
sayHi('Alice'.'Bob')
sayHi('Alice'.'Bob'.'Clair')

// Note that arguments[0] are the same as name1
Copy the code
  1. Arguments also has the length attribute to get the number of arguments
function argLength() {
  alert(arguments.length)
}

argLength('arg1'.'arg2')
Copy the code

3.6.4.2 Basic Type Parameter Transfer

// function refers to the same argument object, the local variable
function add (num) {
  num += 10
  return num
}
  
var count = 20
var result = add(count)
alert(count) // 20 - The original value does not change
alert(result) // 30 - The result of the local variable changes - so function is passed by value
Copy the code

3.6.4.3 Transferring Reference Type Parameters

Arguments and arguments refer to the same object since the object itself is assigned by reference

// Function argument and person refer to the same object in memory,
// So person.name changes, but it does not mean that local variables in function arguments affect global variables
function setName(obj) {
  obj.name="Elanie"
  obj = new object()
  obj.name = "Henry" // Obj overridden only for internal purposes is assigned to Henry without affecting the person.name passed in externally. Overridden obj is destroyed automatically at the end of the function
}

var person = new Object()
setName(person)
alert(person.name) // "Elanie"
Copy the code

3.6.4.4 Addendum: Function can be passed in as an argument

Since function is itself a variable, function can also be passed as an argument

// 1. Pass function as an argument to another function
function add1(num) {
  return num + 1
}

function add2(num2) {
  return num2 + 2
}

var result = add2(add1(10)) / / 13

// 2. Return a function from a function
function createCompareFunction(propName) {
  return function (obj1, obj2) {
    var value1 = obj1[propName]
    var value2 = obj2[propName]
    if (value1 < value2) return -1
    else if (value1 > value2) return 1
    else return 0}}var data = [
  { name: 'name1'.age: 20 },
  { name: 'name2'.age: 28 }
]
data.sort(createCompareFunction('age'))
Copy the code

3.6.5 Function internal Properties – this, arguments

3.6.5.1 the arguments. The callee ()

Note: Callee cannot be used in strict mode

// Take the factorial function as an example:
// 1. General method: The call name must be the same as the function name
function fac (num) {
  if (num <= 1) return 1
  else return num * fac(num - 1) // There is a problem: if the faC variable is reassigned/overwritten later, this function call will fail
}

// 2. Workaround: Use arguments.callee() to eliminate the tight coupling problem so that the recursive call can be completed normally no matter what name is written when calling the function
function fac (num) {
  if (num <= 1) return 1
  else return num * arguments.callee(num - 1) // Eliminate tight coupling and get methods via arguments
}

// Test: Test the factorial function above using arguments.callee()
var trueFac = fac   // trueFac gets fac values, references, and Pointers
fac = function() {  TrueFac: trueFac: trueFac: trueFac: trueFac: trueFac: trueFac
  return 0
}
alert(trueFac(5))  / / 120
							     // The faC uses callee, so it can return normal factorial data.
                   Return num * 0 = 0 in trueFac
alert(fac(5))      / / 0
Copy the code

3.6.5.2 This object: The environment object in which the function is executed

window.color = 'red' 
var o = { color: 'blue' } 
function sayColor () {
  alert(this.color)
}
sayColor()            // 'red' - where this refers to the global environment object window
o.sayColor = sayColor // create the sayColor attribute
o.sayColor()          // The sayColor attribute in 'blue' calls this, which refers to object O, so output blue
// Note: sayColor is still a pointer, both internally and externally to the same pointer variable, but the this object is called differently

// A more elegant way to call: the call() method
Copy the code

3.6.6 Properties and methods of functions

3.6.6.1 length attribute

Length: Number of named arguments you want to receive (not arguments)

function foo0 () {
  return ' '
}

function foo1 (num) {
  return num
}

function foo2 (num1, num2) {
  return num1 + num2
}

foo0.length / / 0
foo1.length / / 1
foo2.length / / 2
Copy the code

3.6.6.2 Prototype Attributes: apply, call, bind

Prototype method use The ginseng arg0 The ginseng arg1 Use the sample
apply() Calling a function in a particular scope,

Set the value of this in the function body **
object Arguments object or argument array sum.apply(this, [arg0, arg1, arg2, ...] )
call() Calling a function in a particular scope,

Sets the value of this in the function body
object Enumerate parameters one by one sum.call(this, arg0, arg1, arg2, ...)
bind() Create an instance of the object and bind this of the object you want to use to function object sum.bind(this)(10, 20)

Points to note:

  1. Prototype saves all instance methods of a reference type, includingtoString(),valueOf()Etc.
  2. The Prototype property is not enumerable and cannot be found using for-in

1. apply()– Sets the value of this object inside the function

function sum(num1, num2) {
  return num1+ num2
}

// The second pass to apply is the Arguments object or array
function callSum1 (num1, num2) {
  return sum.apply(this.arguments)}function callSum2 (num1, num2) {
  return sum.apply(this, [num1, num2])
}
callSum1(10.20) / / 30
callSum2(10.20) / / 30
Copy the code

2. call()– Sets the value of this object inside the function

The arguments passed to the function by the call method must be enumerated one by one rather than passed to the array
function callSum3 (num1, num2) {
  return sum.call(this, num1, num2)
}
callSum3(10.20) / / 30
Copy the code

3. bind()– Creates an instance of the function

// bind method - creates an instance of the function
var objSayColor = sayColor.bind(o) // Make objSayColor's this value o.this instead of global this
objSayColor()   // blue - When called globally, objSayColor gets O.this
sayColor()      // red -- global call, sayColor gets window

// Bind passes arguments - the method is the same as the original method
// Example 1:
function sayColorName(title) {
  alert(title + ":" + this.color)
}
var o ={ color: 'blue' }
var objSayColorName = sayColorName.bind(o)('show this color name')
objSayColorName() // show this color name: blue

// Example 2:
function callSum4 (num1, num2) {
  return sum.bind(this)(num1, num2)
}
callSum4(10.20) / / 30
Copy the code

4. Added:call()andapply()Extension: Objects do not need to be coupled to methods

// Call and apply apply - scoping - objects need not be coupled to methods
window.color = 'red'
var o ={ color: 'blue' }
function sayColor() {
  alert(this.color)
}

sayColor()            // red - Direct call: returns the this.color of the global object
sayColor.call(this)   // red - Pass in the global object this and return this.color
sayColor.call(window) // red - Pass in the global object window and return window.color
sayColor.call(o)      // blue - Pass in the object O and return O.color
SayColor = sayColor * o.saycolor () */
Copy the code

5. Other methods:valueOf()– Returns only the function code

sayColor.valueOf()
ƒ sayColor() {* alert(this.color) *} */
Copy the code

3.6.7 Basic Packing Types

  1. Primitive type values have several wrapped methods for primitive types:var s2 = s1.substring(2)
  2. The main difference between reference types and base wrapper types is the lifetime of the object
    1. Objects of reference type created with new are kept in memory until the execution flow leaves the current scope, and properties and methods can be added at run time
    2. An automatically created primitive wrapper type object that exists only at the moment of execution of a line of code and is then destroyed immediately without adding properties and methods at run time
// New calling the constructor is not the same as using the transition function of the same name directly
var value = '25'
var number = Number(value) // Transition function
alert(typeof number) // number

var obj = new Number(value) // constructor
alert(typeof obj) // object
Copy the code

3.6.7.1 Boolean type

  1. An instance of Boolean overrides the following methods:

    • ValueOf () – Returns the base type value true/false
    • ToString () – Returns string ‘true’/’false’
  2. The difference between a Boolean of a base type and a reference type:

    • The typeof operator returns’ Boolean ‘for primitive types and ‘object’ for reference types
    • Since Boolean objects are instances of Boolean types, when instanceof is used, the object returns true and the primitive type returns false
  3. It is not recommended to use the instantiated method (new method), which can be confusing

3.6.7.2 Number type

  1. The Number type overrides the following methods:
    • ValueOf () – returns the valueOf the base type represented by the object
    • ToString () – Returns a numeric value as a string
  2. The difference between the Number value of a base type and a reference type:
    • The typeof operator returns ‘number’ for primitive types and ‘object’ for reference types
    • Since the Number object is an instanceof type Number, when instanceof is used, the object returns true and the base type returns false
  3. It is not recommended to use the instantiated method (new method), which can be confusing
// Other methods provided by the Number type:
var num1 = 10
var num2 = 10.005

// 1. toFixed - Returns a string representation of a numeric value rounded to the specified decimal place
num1.toFixed(2) / / 10.00
num2.toFixed(2) / / 10.01

// 2. ToExponential representation
num1.toExponential(1) / / 1.0 e+1

// 3. ToPrecision - Return the appropriate numeric format according to the method of when
var num3 = 99
num3.toPrecision(1) // 1e+2
num3.toPrecision(2) / / 99
num3.toPrevision(3) / / 99.0
Copy the code

3.6.7.3 type String

  1. Created using the constructor
var strObj = new Sting('hello world')
Copy the code
  1. length()– Gets the length of the string
var str = 'hello world'
alert(str.length) / / 11
Copy the code
  1. Characters of the method
// 1 charAt() - returns the character at the given position as a single string
var strVal = 'hello world'
alert(strVal.charAt(1))     // e

// 2 charCodeAt - Returns the character in character encoding at the given position
alert(strVal.charCodeAt(1)) / / 101

// 3 Use square brackets [] directly to access characters at a given position (not supported in previous versions of IE8)
alert(strVal[1])            // e
Copy the code
  1. String manipulation method –Concat (), slice(), substr(), substring()
// 1 concatenate () - Concatenate one or more strings, return the concatenated new string (note: the + sign also works)
var str1 = 'hello'
var str2 = str1.concat(' world')         // hello world
var str3 = str1.concat(' world'.'! ')    // hello world!
var str4 = str1 + ' world' + '! '         // hello world!

// 2 slice() - intercepts the string from the start to the end position
var str5 = strVal.slice(3)               // lo world - Defaults to the last bit if the end bit is not specified
var str6 = strVal.slice(3.7)            // lo w - When the end bit is specified, the return string does not contain the last bit

// 3 substr() - intercepts a string from the start position to the end position
var str7 = strVal.substr(3)              // lo world - Defaults to the last bit if the end bit is not specified
var str8 = strVal.substr(3.7)           // lo worl - Returns a string containing the next bit of the last bit when specifying the end bit

// 4 subString () - Intercepts strings from the start position to the end position
var str9 = strVal.substring(3)           // lo world - Defaults to the last bit if the end bit is not specified
var str10 = strVal.substring(3.7)       // lo w - When the end bit is specified, the return string does not contain the last bit
Copy the code
  1. String position method –IndexOf (), lastIndexOf ()
var strVal = 'hello world'

var str11 = strVal.indexOf('o')          // 4 - Query from first to last
var str12 = strVal.lastIndexOf('o')      // 7 - Start with the last digit
var str12 = strVal.indexOf('o'.6)       // 7 - Queries from the 6th digit onwards
var str13 = strVal.lastIndexOf('o'.6)   // 4 - Start with the sixth digit
Copy the code
  1. trim()– Delete the Spaces before and after
// trim() - Deletes pre and post Spaces
var str14 = ' hello '
var str15 = str14.trim()                 // 'hello'
Copy the code
  1. Case conversion
var str16 = strVal.toUpperCase()        // HELLO WORLD
var str17 = str16.toLowerCase()         // hello world
Copy the code
  1. String pattern matching method
// String pattern matching methods - match()/search()/replace() - Similar to the exec() method of calling RegExp, used to match regular expressions or RegExp objects
var text = 'cat, bat, sat, fat'
var pattern = /.at/
var matches = text.match(pattern) // Return an array
alert(matches.index) / / 0
alert(matches[0]) // 'cat'
alert(pattern.lastIndex) / / 0

var pos = text.search(/at/) // 1-at first appears in text

var rep = text.replace('at'.'ond') // cond, bat, sat, fat - Replace string
var rep2 = text.replace(/at/g.'ond') // cond, bond, sond, fond

var sp = text.split(', ') // ['cat', 'bat', 'sat', 'fat'] - Split by symbol
Copy the code
  1. localeCompare()– Compares two strings
// localeCompare() - Compares two strings
/* Comparison rules: * a. If the string should precede the string arguments in the alphabet, return a negative number (-1) * b. Return 0 * c if the string is equal to the string argument. If the string should be ranked after the string argument in the alphabet, return a positive (1) */
var stringValue = 'yellow'
stringValue.localeCompare('bricke') / / 1
stringValue.localeCompare('yellow') / / 0
stringValue.localeCompare('zooooo') // -1
Copy the code
  1. fromCharCode()– Takes one or more string encodings and converts them to strings
// fromCharCode() - takes one or more string encodings and converts them to strings
String.fromCharCode(104.101.108.108.111) // hello 
Copy the code

Table of Notes:

JavaScript Learning (1) – A history of JavaScript

JavaScript Learning (2) – Basic syntax

Learning JavaScript (3)- Talk about prototype chains – 1. Variables

Learning JavaScript (3)- Talk about prototype chains – 2. Objects and prototypes

Learning JavaScript (3)- Talk about prototype chains – 3. Prototype chains and inheritance

JavaScript Learning (4)- Talk about closures

Github:

Github Notes link (continue to update, welcome star, please mark source for reprint)