ES6 箭头函数及this

ES6 箭头函数及this

1、箭头函数

<script type="text/javascript">
    //以前定义函数
    let fun=function () {
        console.log('123');
    }
    fun();
    //现在可以简化下,用箭头函数
    let fun1=()=>{
        console.log('123');
    }
    fun1();
    //然后假如函数体只有一条语句或者是表达式的时候{}可以省略
    let fun2=()=>console.log(123);
    fun2();
    //加形参情况
    let fun3=(a)=>console.log(a);
    fun3('123');
    //只有一个形参的时候 ()可以省略
    let fun4=a=>console.log(a);
    fun4('123');
    //多个形参
    let fun5=(x,y)=>console.log(x,y);
    fun5('123','456')
</script>

2、this

箭头函数没有自己的this,箭头函数的this不是调用的时候决定的,而是再定义的时候所在的对象就是它的this

箭头函数的this看外层是否有函数,

  如果有,外层函数的this就是内部调用箭头函数的this 

  如果没有,则this是window

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button id="btn1">按钮1</button>
<button id="btn2">按钮2</button>
<script type="text/javascript">
    let btn1=document.getElementById('btn1');
    let btn2=document.getElementById('btn2');
    btn1.onclick=function(){
        alert(this);//按钮1 这里的this是 调用的时候的btn1对象;
    };
    btn2.onclick=()=>{
        alert(this);//按钮2,this是window对象;
    }
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button id="btn1">按钮1</button>
<button id="btn2">按钮2</button>
<script type="text/javascript">
    let btn1=document.getElementById('btn1');
    let btn2=document.getElementById('btn2');
    //不用箭头函数
    let obj1={
        name:'jack',
        age:11,
        getName(){
            btn1.onclick=function(){
                console.log(this);
            }
        }
    }
    obj1.getName();//this 就是按钮1

    let obj2={
        name:'jack1',
        age:11,
        getName() {
            btn2.onclick =()=>console.log(this);
        }
    }
    obj2.getName();//this 就是 obj2,因为箭头函数是定义再对象的回调方法里,所以这里的this是obj2;

</script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/jnba/p/12196761.html
今日推荐