image.png

this基本情况:

  1. 1.函数形式调用:window
  2. 2.方法的形式调用:调用的方法
  3. 3.构建函数:新创建的对象
  4. 4. callapply调用:指定的对象
  1. <script>
  2. /* 怎么理解函数内部this的指向 */
  3. /* tips:this取什么值,是在函数执行的时候确定,而不是定义时确定 */
  4. /* 1.普通函数中的this --指向window*/
  5. function go(){
  6. console.log(this);
  7. }
  8. </script>
  1. <button id="btn">btn</button>
  2. <script>
  3. var btn = document.getElementById("btn");
  4. btn.onclick = function(){
  5. setTimeout(function(){
  6. console.log(this); //window
  7. },500)
  8. }
  9. </script>
  1. <script>
  2. /* 2. 作为对象的方法调用 */
  3. /* 3.在箭头函数中this */
  4. var name = "window"
  5. var obj = {
  6. name:"javascript",
  7. sayName(){
  8. console.log(this.name); //javascript
  9. },
  10. wait(){
  11. console.log(this.name);//javascript
  12. setTimeout(function(){
  13. console.log(this.name); //window
  14. },500)
  15. },
  16. delay(){
  17. setTimeout(()=>{
  18. console.log(this.name); //javascript
  19. })
  20. },
  21. layout(){
  22. setTimeout(function(){
  23. console.log(this.name);
  24. }.bind(this)) //bind改变函数关键字
  25. },
  26. print(){
  27. var that = this;
  28. setTimeout(function(){
  29. console.log(this.name); //javascript
  30. }.bind(that))
  31. }
  32. }
  33. obj.sayName();
  34. obj.wait();
  35. obj.delay();
  36. obj.delay();
  37. obj.print()
  38. </script>
  1. <script>
  2. /*4. call,apply,bind */
  3. function fn1(){
  4. console.log(this);
  5. }
  6. var obj = {
  7. name:"vue"
  8. }
  9. fn1();
  10. fn1.call(obj);
  11. var fn2 = fn1.bind(obj);
  12. fn2();
  13. </script>
  1. <script>
  2. /* 5.class this */
  3. /* 在class类和构造函数中this指向使用new关键字实例化的对象 */
  4. class Person{
  5. skill ="lisi";
  6. constructor(name,age){
  7. this.name = name;
  8. this.age = age
  9. }
  10. }
  11. var p = new Person("lisi",18);
  12. console.log(p.name);
  13. </script>