让前端飞我爱编程

js函数this的指向

2018-04-12  本文已影响45人  EdmundChen

箭头函数 (()=>{})

function(){}

1. 非严格模式
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <p>hello word</p>
</body>
<script type="text/javascript">
    function getName(){
        console.log('this', this);
    }

    getName() // window

    const a = {
                name: 'xxx'
        getName
    }
    a.b() // object a
</script>
</html>

详细看apply, call, bind方法

2. 严格模式

在严格模式下,未指定环境对象而调用函数,则this值不会转型为window。除非明确把函数添加到某个对象或者调用apply(),call(), bind,否则this值将是undefined

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <p>hello word</p>
</body>
<script type="text/javascript">
    'use strict'
    // 验证第一条剪头函数this指向
    const getName = () => { console.log(this) }
    getName() // window

    function getAge(){
        console.log('this', this);
    }
    getAge() // undefined
    const obj = {
                name: 'xxx',
                age: 32,
                getAge,
                getName
               }
    obj.getAge() // object a
    obj.getName() // window
</script>
</html>
上一篇 下一篇

猜你喜欢

热点阅读