在js中lambda表达式是为了代替匿名方法,优化代码格式
setTimeout(function(){
console.log("打印内容");
},1000);
setTimeout(()->{
console.log("打印内容");
},1000);
而在js中特别要注意this问题,在箭头函数中this是指向object的
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<!--
箭头函数 不能作为构造器
-->
<body>
<button type="button" id="btn1">点我</button>
<script type="text/javascript">
let btn = document.getElementById("btn1");
btn.addEventListener('click',function(){
//箭头函数中的this指向函数定义生效时所在的对象
window.setTimeout(()=>{
console.log(this);
this.style.background="green"
},1000)
});
</script>
</body>
</html>
在浏览器的打印界面中并未打印出此时的this指向,是显示Object
所以需要在外部定义this的指向
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button type="button" id="btn1">点我</button>
<script type="text/javascript">
btn.addEventListener('click',function(){
// console.log(this);
let _this = this
window.setTimeout(function(){
console.log("this指向:"+this);
_this.style.background = "red"
},500)
})
</script>
</body>
</html>
此时的打印结果就变成了 window
在Java中没有匿名方法,但是为了这种lambda写法,提供了函数接口式编程,也就是只有一个抽象方法的接口,而且需要在类上方打上@FunctionalInterface
这种函数式编程,顺利推导出了lambda表达式