Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

js属性方法里面的函数this指向

<div style="width: 100px; height: 100px; background:#ccc;" onclick="obj.a()"></div>
  <div style="width: 100px; height: 100px; background:#ccc;" onclick="a()"></div>
<script>
  let obj = {
    a(){
      alert(this)
      function b(){
        alert(this)
      }
      b()
    },
  }

  function a(){
    alert(this)
    function b(){
      alert(this)
    }
    b()
  }
</script>

为什么调用属性方法的时候 a里面的b函数this指向了window,而调用函数的时候a和b都指向window


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

函数体内的this。由是谁调用的来决定~


let obj = {
    a(){
      alert(this)
      function b(){
        alert(this)
      }
      b()
    },
}
  • 执行obj.a()时,a由obj调用,所以obj.a里面的this为obj
  • b 里面的this,当执行obj.a()执行时,函数体提升,执行b(),相当于window.b(),所以b中this为window。另:由于函数b中无闭包,执行完即释放。
  • b 函数为 箭头函数,则会继承外层函数a的this, 此时b中this会为a

function a(){
    alert(this)
    function b(){
        alert(this)
    }
    b()
}
  • 若执行上述函数方法a() 相当于window.a(),同理。
  • 可以把函数复制在浏览器console控制台,然后输入window.a测验

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...