箭头函数
箭头函数和普通函数有什么区别?如果把箭头函数转换为不用箭头函数的形式,如何转换
主要是this的差别,箭头函数里面的this是外面的this。 转换案例
箭头函数和普通函数的主要区别是箭头函数的 this
是外部环境的
const obj = {
a: 1,
fn: () => {
console.log(this.a)
}
}
//转换成
var _this = this
var obj = {
a: 1,
fn: function fn() {
console.log(_this.a)
}
}
箭头函数内定义的变量及其作用域
// 常规写法
var greeting = () => {let now = new Date(); return ("Good" + ((now.getHours() > 17) ? " evening." : " day."));}
greeting(); //"Good day."
console.log(now); // ReferenceError: now is not defined 标准的let作用域
// 参数括号内定义的变量是局部变量(默认参数)
var greeting = (now=new Date()) => "Good" + (now.getHours() > 17 ? " evening." : " day.");
greeting(); //"Good day."
console.log(now); // ReferenceError: now is not defined
// 对比:函数体内{}不使用var定义的变量是全局变量
var greeting = () => {now = new Date(); return ("Good" + ((now.getHours() > 17) ? " evening." : " day."));}
greeting(); //"Good day."
console.log(now); // Fri Dec 22 2017 10:01:00 GMT+0800 (中国标准时间)
// 对比:函数体内{} 用var定义的变量是局部变量
var greeting = () => {var now = new Date(); return ("Good" + ((now.getHours() > 17) ? " evening." : " day."));}
greeting(); //"Good day."
console.log(now); // ReferenceError: now is not defined
立即执行函数
- 声明一个匿名函数
- 马上调用这个匿名函数
!function(){}()
作用
创建一个独立的作用域,即避免变量污染
var liList = ul.getElementsByTagName('li')
for(var i=0; i<6; i++){
liList[i].onclick = function(){
alert(i) // 为什么 alert 出来的总是 6,而不是 0、1、2、3、4、5
}
}
var liList = ul.getElementsByTagName('li')
for(var i=0; i<6; i++){
!function(ii){
liList[ii].onclick = function(){
alert(ii) // 0、1、2、3、4、5
}
}(i)
}
网友评论