1. // 非严格模式下
    2. function hello() {
    3. console.log(this) // this 指向 window
    4. }
    5. hello()

    图片.png

    1. 'use strict'
    2. function hello() {
    3. console.log(this) // undefined
    4. }
    5. hello()
    6. // 不要依赖函数内部的 this
    1. // 谁调用了这个函数,this 就是谁
    2. const obj = {
    3. name: 'haru',
    4. hello: function () {
    5. console.log(this.name + 'haha')
    6. }
    7. }
    8. obj.hello()

    图片.png

    1. // window.name 有值
    2. // 'use strict' :
    3. // use strict 情况下 hello1() 点用 打印 console.log(this.myName) 会出现如下错误
    4. // Uncaught TypeError: Cannot read properties of undefined (reading 'myName')
    5. const obj = {
    6. myName: 'haru',
    7. hello: function () {
    8. console.log(this.myName + 'haha') // undefined
    9. }
    10. }
    11. let hello1 = obj.hello() // TODO WHY
    12. hello1() // 虽然函数赋值了 obj.hello(), 调用时 hello() 自己调用, 没有 obj. 开头, 失去了绑定关系
    1. const obj = {
    2. myName: 'haru',
    3. hello: function() {
    4. console.log('params', argument)
    5. console.log(this.myName + 'haha') // haru haha
    6. }
    7. }
    8. let hello1 = obj.hello()
    9. hello1()
    10. // 可以用 call / apply 来改变函数内部的 this
    11. hello1.call(obj, 345, 456)
    12. hello1.apply(obj, [345, 456])
    13. let hello2 = hello1.bind(obj)
    14. hello2(123)
    1. // dom 操作
    2. <body>
    3. <button id='app' data-name='haru'>btn</button>
    4. <script>
    5. document.querySelector('#app').addEventListener('click', function() {
    6. console.log(this) // <button id='app' data-name='haru'>btn</button>
    7. this.innerText = 'xx'
    8. console.log(this.getAttribute('data-name'))
    9. }, false)
    10. <script>
    11. </body>
    let obj = {
      myName = 'haru',
      hello: function () {
         // const self = this // TODO WHY
         // function demo () {
         //     console.log(self.myName + 'haha') // haru
         // }
        function demo() {
          console.log(this.myName + 'haha') // undefined
        }
        demo()
      }
    }
    
    // 箭头函数 没有 arguments, 没有 this
    let obj = {
      myName = 'haru',
      hello: function() {
        const demo = () => {
          console.log(this.myName + 'haha') // haru
        }
        demo()
      }
    }
    
    obj.hello()
    
    const test1 = (a, b, c = 1) {
      console.log( a + b)
      // 箭头函数不需要写 return 关键字
      // return a*2
    }
    
    const test2 = item => item*2