javacript中function (res) {}与(res) =>{}的区别
function (res) {} 代码演示
let shape = {
name:'长方形',
say:function(){
console.log('我是'+this.name)
setTimeout(function(){
console.log('3秒后输出我是: ' + this.name); //this.name为undefined
}, 3000)
}
}
shape.say()
箭头函数表达式(lambda表达式),(res) =>{}
lambda表达式 ()=>{something}或()=>something 相当于js中的函数,它的好处是可以自动将函数中的this附加到上下文中
将上面的function(){} 改成 ()=>{}
let shape = {
name:'长方形',
say:function(){
console.log('我是'+this.name)
setTimeout( ()=>{
console.log('3秒后输出我是: ' + this.name); //this.name可以正常输出
}, 3000)
}
}
shape.say()