ES5-19 变量声命周期、垃圾回收原理、arguments
變量聲命周期
垃圾回收
- 解除由于閉包產(chǎn)生的對fn AO的引用
標(biāo)記清除
- 排除全局變量、排除閉包引用的AO中的變量
- 進(jìn)入環(huán)境 → 離開環(huán)境
- 常用
引用計(jì)數(shù)
- 引用計(jì)數(shù)為0時(shí)清除
- 對循環(huán)引用的情況,如果不手動(dòng)接觸引用(a = null),則無法清除
arguments
屬性
- 函數(shù)內(nèi)部對應(yīng)參數(shù)值的實(shí)參列表
- 類數(shù)組對象 Array-like
- 有屬性callee,指向它的宿主函數(shù)
- 屬性Symbol(Symbol.iterator) 表示可迭代
- constructor是Object
- 有l(wèi)ength屬性
- 屬性下標(biāo)從0開始
- 沒有數(shù)組的內(nèi)置方法
- 注意:箭頭函數(shù)沒有arguments
普通對象是不可迭代的
- 三個(gè)參數(shù),迭代到第四個(gè)便完成了
箭頭函數(shù)內(nèi)使用實(shí)參(es6弱化了arguments)
- 嚴(yán)格模式讓arguments和eval少了一些奇怪的行為。兩者在通常的代碼中都包含了很多奇怪的行為。
Strict mode makes arguments and eval less bizarrely magical. Both involve a considerable amount of magical behavior in normal code.
arguments的一些操作會(huì)阻止js引擎的優(yōu)化
對參數(shù)使用slice會(huì)阻止某些JavaScript引擎中的優(yōu)化 (比如 V8 - 更多信息)。如果你關(guān)心性能,嘗試通過遍歷arguments對象來構(gòu)造一個(gè)新的數(shù)組。另一種方法是使用被忽視的Array構(gòu)造函數(shù)作為一個(gè)函數(shù)
var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments));
bluebird-petkaantonov
- 多種方式將arguments轉(zhuǎn)為新數(shù)組返回
使用場景:
形、實(shí)參的對應(yīng)關(guān)系
Note: If you’re writing ES6 compatible code, then rest parameters should be preferred.
Note: “Array-like” means that arguments has a length property and properties indexed from zero, but it doesn’t have Array’s built-in methods like forEach() and map(). See §Description for details.
當(dāng)非嚴(yán)格模式中的函數(shù)沒有包含剩余參數(shù)、默認(rèn)參數(shù)和解構(gòu)賦值,那么arguments對象中的值會(huì)跟蹤參數(shù)的值(反之亦然)。
1. 形參中但凡有一個(gè)有默認(rèn)值, 形、實(shí)參不再對應(yīng)
function test(a = 100, b, c) {arguments[1] = 1000console.log(b, arguments[1]) // 2 100 } test(1, 2, 3)不統(tǒng)一的具體表現(xiàn)
1. ES6形參默認(rèn)值
2. ES6使用展開運(yùn)算符
function test(...args) {arguments[0] = 100console.log(args[0], arguments[0]) // 1 100 } test(1)3. ES6參數(shù)解構(gòu)
function test({ a, b, c }) {arguments[0]['a'] = 100console.log(a, arguments[0]['a']) // 1 100 } test({ a: 1, b: 2, c: 3 })MDN: 注意: 在嚴(yán)格模式下,arguments對象已與過往不同。arguments[@@iterator]不再與函數(shù)的實(shí)際形參之間共享,同時(shí)caller屬性也被移除。
4*. 嚴(yán)格模式下,怎么都不對應(yīng)
function test(a, b, c) {'use strict'arguments[0] = 100console.log(a, arguments[0]) // 1 100 } test(1)5. ES5實(shí)參undefined
var test = function (a, b) {a = 1console.log(a, arguments[0]) // 1 undefined } test() // 這個(gè)相當(dāng)于es5無默認(rèn)值 var test = function (a = undefined, b) {console.log(a, arguments[0]) // 100 100 } test(100)arguments
總結(jié)
以上是生活随笔為你收集整理的ES5-19 变量声命周期、垃圾回收原理、arguments的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黑马微服务项目乐优商城全套
- 下一篇: ES5-20 复习