JS summing (1) - variable Environment

1. Data

1.1 Data Types

The basic data Undefinedtypes: Null, Boolean, Number, String, , Symbol
reference data types:Object

1.2 Data storage

Basic data types are stored in the stack memory, the value of the variable value that is actual data, the assignment of the variable is the value of the copy.

const num1 = 5 // 在栈内存中生成一个值为5的数据赋值给num1
const num2 = num1 // 在栈内存中再次生成一个值为5的数据赋值给num2
// num1 和 num2 实际是两片不同的栈内存数据,只是值相同,互相独立

Reference data type is stored in the heap memory, the address value of the variable is the actual data, for copying copy variable address.

const obj1 = {} // 在堆内存中生成一个空对象,将对象的引用地址赋值给obj1
const obj2 = obj1 // 不对堆内存做任何操作,将对象obj1的引用地址复制给obj2
// obj1 和 obj2 实际是同一片堆内存数据,除变量名不同外,两者完全相同,修改对象会互相影响

1.3 Detection and comparison data

typeofDetection variable data type. NOTE: typeof null = 'object'
equal to ('=='): compare the conversion is automatic when the data types. Note: The reference data types call the valueOfmethod

const obj1 = {}
const obj2 = {
    valueOf () { return 1 }
}
console.log(obj1 == 1, obj2 == 1) // false true

Congruent ('==='): Comparison of data types and values are relatively address is reference data types

2. Variable

2.1 define the variable

JS variables are loose type, can be used to store any type of data, the default value undefined
var: the variables declared in advance to the top of the scope, using the default value prior to the definition, a statement may be repeated the same variable, modify the value
const: None declared in advance can not be defined prior to use, the definition can not be repeated, can not be modified values
let: no declaration in advance, can not be used before the definition, the definition can not be repeated, the value can not be modified

2.2 advance statement

Variables declared in advance: the use of var definition of variables, variables declared at the top level function assignment in the Run line

console.log(a, b) // undefined undefined
if (false) {
    var a = 10
} else {
    var b = 10
    (function f() {
        console.log(c) // undefined
        var c = 10
        console.log(c) // 10
    }())
}
console.log(a, b) // undefined 10
console.log(c) // 报错

Function declaration in advance: when declaring a function, the function will be moved up to the top of the scope and definitions. Note: The function expression does not declare in advance.

f1() // 1
function f1() {
    console.log(1)
}
f2() // 报错
if (1) {
    // f2只会被提前到这
    function f2() {
        console.log(2)
    }
}
f2() // 2

Priority function: function declaration in advance priority greater than the variable declarations. (More likely to be due to personal function declaration comes assignment, but only to enhance the variable declaration)

// function f1 和 var f1都被提升到这
// 如 function f1在前,那么var f1后运行时f1这个变量已存在,var f1失效
// 如 var f1在前,那么function f1后运行,f1这个变量已存在,不再定义新变量,将function赋值给f1
// 无聊哪种情况f1的值最终都会是function f1的值,因此个人觉得不存在优先级问题
f1() // 1
var f1
f1() // 1
var f1 = function () {
    console.log(2)
}
f1() // 2
function f1() {
    console.log(1)
}

2.3 Scope

Used const, letdefined variables that can be used only in the current block

{
    // console.log(a) // 报错
    const a = 1
    console.log(a) // 1
    // const a = 2 // 报错
}
console.log(a) // 报错,a is not defined

2.4 with a global scope and function domain

Global scope: the scope outermost
function scope: generating an execution environment similar to block scope

3. Environment

3.1 Scope chain

To ensure orderly access to all variables and functions have access to the execution environment of
access rules:

  • The scope of the same layer have the same access rights
  • Outer scope can not access the internal scope
  • Internal scope can access external scope
  • Scopes with different internal layer can not access each other
  • Variable access follow the principle of proximity (to get the current value of the variable scope of the recent distance)

3.2 Environmental context

Generally understood as the scope chain, i.e., the current position variable accessible
can avatar as an object, the object comprising the following:

  1. The current variable accessible: value of the variable
  2. Functions currently accessible: the value of the function
  3. this: the value of this

The difference between the scope chain is:

  • The scope and the scope chain have been identified in the definition of variables accessible
  • Environmental context not only accessible variables, but also the value of the variable. Since the value is changed at run time, only to perform in the current context to determine the specific value

3.3 this

Called the current function of the target
binding rules:

  1. Default binding: direct calls without any modification, this points to the global object
function f () { return this }
console.log(f()) // window, 没有全局对象则是undefined
  1. Implicit binding: Called by the target chain, this points to the calling object
function f () { return this }
const obj = {
    f: f
}
console.log(obj.f() === obj) // true
  1. Hard binding: .call, .apply, .bind
function f () { return this }
const obj = {}
console.log(f.call(obj) === obj) // true
  1. new binding: new constructor
function f (a) { this.a = a }
const obj = new f('a')
console.log(obj.a) // 'a'
  1. Arrow function:
const that = this
const obj1 = {
    a: 'a',
    f: () => {
        console.log(this === that)
    }
}
const obj2 = { a: 'b' }
obj1.f.call(obj2) // true

4. Closure

4.1 What is a closure

Closure: Exponent function has access to another variable domain of action

var result
function heal(HP, healer) {
    return function(currentHP, target) {
        console.log(
        `${target} get ${HP} point heal from ${healer}, total HP is ${currentHP + HP}`
        )
    }
}
heal(100, 'Soraka')(500, 'Teemo') // Teemo get 10 point heal from Soraka, total HP is 600

4.2 function generator shown

The resulting product function:

  • Generating an execution environment and scope chain
  • Generate active object function

heal function generator shown:

Here Insert Picture Description
Closure function generating an illustrative:
Here Insert Picture Description

4.3 garbage collection

4.3.1 Clear labeling

Prefer to call up individual algorithms, logic is as follows:

  1. From now traversing node down, the variable and all the variables accessible variables referenced marked
  2. Traversal again, clear all variables unmarked
4.3.2 reference count

Defects, thus with less

  1. Each value is the number of times referenced by the variable record. Assigned to variables, plus a reference number; dereferences variable (reference variable or other release values), the number of references is decremented
  2. Release all references to the number of variables to zero

Defects:
circular reference can not be released, such as object A references object B, the object B also references objects A, but A and B are not variables can be accessed

Closures produced 4.4

No closure case:

  1. Function that generates an execution environment in function and scope chain
  2. After the implementation of release and the scope chain execution environment
  3. Garbage collection work, because the object is no longer a function of variables have variable references, can not get to destroy an object variable function

Closures have produced where:

  1. Generating heal function execution environment and scope chain. Scope chain point: heal the variable object, global variable objects
  2. Generate anonymous function execution environment and the scope chain. Points to the scope chain: variable objects anonymous function, heal the target variable, the global variable object
  3. heal function completes the function returns a reference to an anonymous address, to destroy and heal function scope chain execution environment
  4. Garbage collection work, as a function of variable objects heal is a visiting anonymous function scope chain, will not be destroyed
  5. Performing anonymous function, generating closures

Closure role 4.5

  1. For variable internal access functions
  2. Stop function calls the data has been cleared
  3. Conducive to packaging, to avoid contamination

4.6 usage scenarios

  1. Callback parameter passing
async function check (callback) {
    const isCheck = await api.check() // 后台获取状态
    return callback(isCheck)
}

check((isCheck) => {
    if (isCheck) {
        console.log('checked')
    } else {
        console.log('Not check')
    }
})
  1. Constructor
function Hero(name, age) {
    this.name = name
    this.age = age
    this.introduction = function () {
        console.log(`my name is ${name}, my age is ${age}`)
    }
}
const Soraka = new Hero('soraka', 18)
Soraka.introduction()
  1. setTimeout parameter passing
function check (res) {
    return function () {
        console.log(res)
    }
}
setTimeout(check(1), 1000) // 原生无法传参,传入会报错
  1. Loop binding events
const divList = document.getElementsByClassName('div')
Array.from(divList).forEach((item) => {
    item.addEventListener('click', () => {
        console.log(item.innerHTML)
    })
})
  1. Module mechanism

Individuals can not certainly achieve JS module is complete closure, but a similar effect.

Module implementation mechanism is code running in the outer call a function in the module file and returns an object

function module() { // JS运行时添加
	// 模块中的代码
    const num= 1	// 模块中的变量
    return {	// 类似 export default {}
        getNumber () {
            console.log(num)
        }
    }
}
const numObj = module() // 类似 import numObj from 'module'
numObj.getNumber() // 调用模块中的函数并范围变量
Released six original articles · won praise 0 · Views 83

Guess you like

Origin blog.csdn.net/weixin_44844528/article/details/104440551