1-普通函数、全局作用域、定时器

  1. ##this指向window
  2. //普通函数中的this 指向window
  3. function go(){
  4. console.log(this);
  5. }
  6. go();//window
  7. //定时器
  8. <button id="btn">btn</button>
  9. <script>
  10. var btn = document.getElementById("btn");
  11. btn.onclick = function(){
  12. setTimeout(function(){
  13. console.log(this);//window
  14. },500)
  15. }
  16. </script>

2-方法

  1. #this指向调用它的对象
  2. <script>
  3. var name = "window"
  4. var obj = {
  5. name:"javascript",
  6. sayName(){
  7. console.log(this.name);
  8. },
  9. wait(){
  10. console.log(this.name);//javascript
  11. setTimeout(function(){
  12. console.log(this.name);
  13. })
  14. },
  15. delay(){
  16. setTimeout(()=>{
  17. console.log(this.name);
  18. })
  19. },
  20. layOut(){
  21. setTimeout(function(){
  22. console.log(this.name);
  23. }.bind(this))
  24. },
  25. print(){
  26. var that = this;
  27. setTimeout(function(){
  28. console.log(this.name);
  29. }.bind(that))
  30. }
  31. }
  32. obj.sayName();//javascript
  33. obj.wait();//window
  34. obj.delay();//javascript
  35. obj.layOut();//javascript
  36. obj.print();//javascript
  37. </script>

3-构造函数和class中

  1. #this指向使用new关键字实例化的对象
  2. function Fun(){
  3. console.log(this); //this指向的是fun 实例对象 指向创造的新对象,新对象赋值给了fun
  4. }
  5. var fun = new Fun()
  6. class Person{
  7. skill = "vue";
  8. constructor(name,age){
  9. this.name = name;
  10. this.age = age;
  11. }
  12. }
  13. var p = new Person("lisi",18);
  14. console.log(p.name); //lisi

4-call、bind、apply

image.png

  1. this指向当前上下文的this
  2. <script>
  3. function fn1(){
  4. console.log(this);
  5. }
  6. var obj = {
  7. name:"vue"
  8. }
  9. fn1.call(obj)
  10. fn1();
  11. var fn2 = fn1.bind(obj);
  12. fn2()
  13. </script>