箭头函数中的this指向

2019-06-09  本文已影响0人  coffee1949
<script type="text/javascript">
    
    // es5
    function sum(){
        console.log(this)
    }
    sum()       
    // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}


    // es6箭头函数
    var sum1 = ()=>{
        console.log(this)
    }
    sum1()      
    //Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
   
</script>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>es6-let</title>
</head>
<body>
    <burron id="app">点我</burron>

<script type="text/javascript">
    var app = document.getElementById('app');
    
    // es5
    // app.onclick = function(){
    //     console.log(this)       //指向触发事件的当前元素对象
    // }
   

    // es6箭头函数
    app.onclick = ()=>{
        console.log(this)  
        // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
    }

    // 总结: 作为事件处理函数,es5的this指向触发当前事件的对象元素,es6箭头函数指向window
   
</script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读