this -> JS 关键字
当前环境执行期上下文
this在不同的环境,不同作用下,表现不同

全局作用域下this —> 全局对象
window 和 this 的关系
web —> window
node —> global
worker —> self
通用 —> globalThis

谁调用函数,函数内容的执行默认就是谁

类的this

类的本质就是函数
class xxx -> 容器/作用域/模块
类是严格模式

  1. class Test1(){
  2. constructor(){
  3. }
  4. static do(){}
  5. say(){}
  6. }
  7. const Test = (function () {
  8. function Test2(){ // constructor
  9. }
  10. Test.prototype.say = function (){}
  11. Test.prototype.do = function (){}
  12. window.Test = Test;
  13. })();
  14. class Test {
  15. constructor(){
  16. // 类的非静态方法 -> new -> this -> {} -> test方法和age属性
  17. this.age = 22;
  18. this.test = function(){
  19. }
  20. }
  21. // 类原型上的静态方法 -> Test.prototype{...}
  22. test(){}
  23. }
  24. // 继承
  25. class Father {
  26. constructor(){
  27. // 基类 no this binding, 因为没实例没调用
  28. //new -> this -> {} -> age属性
  29. this.age = 44;
  30. }
  31. swim() {
  32. console.log('swimming');
  33. }
  34. }
  35. class Son extends Father {
  36. constructor(){
  37. // 调用Father上的constructor
  38. // 生成this绑定 -> Father this -> son的实例上
  39. // this -> new Father() -> {}
  40. super();
  41. this.name ='son';
  42. }
  43. study(){
  44. this.swim();
  45. }
  46. }

call/apply/bind this

var newFn = function test(a,b,c) {
this ->window ->context
}.bind(context);
bind与call/apply区别:
bind不会立即执行函数,而是返回一个新的函数,这个新的函数绑定上下文(context)
call/apply 立即执行函数,并且将this指向改为context

  1. var initModule = (function(){
  2. return {
  3. a: 1,
  4. b: 2,
  5. plus: function() {
  6. return this.a + this.b;
  7. }
  8. })(); // 立即执行函数,执行完返回一个对象,对象赋值给initModule
  9. console.log(initModule) // {a:1,b:2,plus:f}
  10. var obj = {
  11. a: 1
  12. }
  13. var obj2 = {
  14. a:100
  15. }
  16. var a = 2;
  17. function test(){
  18. // this 默认 -> 全局对象window
  19. console.log(this.a)
  20. }
  21. test();
  22. test.call(obj);
  23. test.apply(obj);
  24. //bind 只生效一次
  25. var test1 = test.bind(obj,3,4);
  26. test1(); //1,3,4
  27. var tes2 = test.bind(obj,3,4);
  28. test2(); // 1,3,4

箭头函数中的this

  1. var obj = {
  2. a: 1
  3. }
  4. var a = 2;
  5. const test = () => {
  6. consloe.log(this.a);
  7. }
  8. test();//2
  9. // 箭头函数是忽略任何形式的this指向的改变
  10. // 静态this指向
  11. test.call(obj); //2
  12. test.apply(obj); //2
  13. var test1 = test.bind(obj); //2
  14. test1();
  15. // 箭头函数一定不是一个构造器
  16. new test(); //报错
  17. // 箭头函数的this不是谁绑定指向谁
  18. obj.test = () => {
  19. console.log(this); // window
  20. }
  21. // 箭头函数 this -> 外层作用域的this指向

对象的this

this 的指向的基本原则: 谁调用this的宿主,this就指向谁
对象方法的内部this -> 最近的引用
image.png
把t函数是一个孤立的函数

new

  1. function Test(){
  2. // new过程
  3. // this-> {}
  4. // { a: 1 }
  5. // { a:1, b:2 }
  6. // return this
  7. this.a = 1;
  8. this.b = 2;
  9. console.log(this);
  10. //默认 return this;
  11. // return { c:3, d:4} // 忽略return this
  12. }
  13. new Test(); // -> { a:1, b:2 }

事件处理函数中的this

事件(onclick)处理函数内部的this指向被绑定DOM元素

  1. oBtn.addEventListener('click', this.handleBtnClick.bind(this), false);