let
和const
let
和var
ES5使用var
声明变量并没有块级作用域,会造成for
循环的变量污染,变量名重复和变量提升的问题。
ES6新增let
声明变量,变量只在代码块中有效,不存在变量提升的问题。- 暂时性死区
TDZ
const
和let
声明变量前均为暂时性死区,在暂时性死区中,变量不能够被使用。
TDZ的本质:进入作用域后,变量已存在但声明后才可获取。 const
声明常量,且必须初始化。
本质维护内存栈中的保存的数据或地址不变,因此基本数据类型不会改变,引用数据类型可以增添修改属性。
字符串的拓展
- 字符串遍历器接口
for of
可直接遍历字符串,但最大优点在于可识大于0xFFFF码点的字符串。 - 字符串的拓展方法
- 确定字符串是否存在
includes()
,startsWith()
,endsWith()
let str = "hello world" str.includes("o") //true str.includes("")//true str.startsWith("hello")//true str.endsWith("world")//true
- 重复字符串
"x".repeat(3)//"xxx"
- 补全字符串
"1".padStart(10,"0")//0000000001 "12".padStart(10,"YYYY-MM-DD")//YYYY-MM-12
- 模板字符串
${expression}
来表示多行字符串,或变量和函数 表达式
函数的拓展
- 参数默认值
- ES5变通给函数参数添加默认值,但必可避免
false
的情况
function log(x,y){
y=y || 'world'
console.log(x,y)
}
log('hello')//"hello world"
log('hello','')//"hello world"
//ES6中
function log(x,y="world"){
console.log(x,y)
}
log("hello","")//"hello"
function log(x=1,y=2){
console.log(x,y)
}
log(undefined,null)//1,null
length
属性,返回没有指定默认值参数的个数。
本质上是预期传入函数的参数个数,因此rest
参数并不包括在内。
rest
参数rest
参数,用于获取函数多余的参数。替代了arguments
注:rest
参数必须是最后一个参数- 严格模式
ES6规定,只要函数参数使用默认值,内部不可声明为use strict
- 箭头函数
- 箭头函数的
this
永远指向声明创建的对象,而不是ES5中指向执行的对象。
function Timer(){
this.s1 = 0
this.s2 = 0
setInterval(() => this.s1++,1000 )
setInterval(function(){
this.s2++
},1000)
}
var timer = new Timer()
setTimeout(() => console.log("s1",timer.s1),3100 )
setTimer(() => console.log("s2",timer.s2),3100)
//s1 3
//s2 0
- 箭头函数不能作为构造函数
原因:箭头函数中的并没有自己的this
,而是指向外部的this
。因此this
指向固化,并且不能作为构造函数new
来源:CSDN
作者:代码写的完嘛
链接:https://blog.csdn.net/qq_40781291/article/details/104493278