如何全面的判断 this 指向

    技术2022-07-11  78

    this

    this 是状态机,是动态变化的对象,随着作用域改变而改变,只能指向对象

    一个没有作用域的语法糖 是没有 this 的

    语法糖:由 sj 代码片段形成的具有功能型的 api

    原理

    函数在执行的时候,会创建一个上下文对象,产生一个局部作用域,函数被谁调用,就指向谁

    判断 this 在作用域中的指向
    // 全局下,this 都指向 window console.log(this); // window function foo(){ console.log(this); // window } (function(){ console.log(this); // window })() function foo(){ return function(){ console.log(this); // window } } (function foo(){ return function(){ console.log(this); // window } })()() // 构造函数中,this 指向 new 实例化的对象 function Person(name,age,sex){ this.name = name; this.age = age; this.sex = sex; this.do = function(){ console.log(this); } } var student = new Person('张三',18,'男'); student.do(); // Person {name: "张三", age: 18, sex: "男", do: ƒ} // 对象中this指向window,谁调用的函数,则指向谁 var person = { name:'李四', age:19, sex:'男', done:this, do:function(){ console.log(this); } } console.log(person.done); // window person.do(); // {name: "李四", age: 19, sex: "男", done: Window, do: ƒ} // call() apply() bind()() 参数指定 this 指向的对象 function foo(){ console.log(this) } foo.call(person); // {name: "李四", age: 19, sex: "男", done: Window, do: ƒ} // 事件处理函数中,this 指向的是【触发事件的元素】,不是绑定事件的元素

    call()

    参数一:指定 this 指向的对象

    参数二~N:给调用函数传入实参

    apply()

    参数一:指定 this 指向的对象

    参数二:数组,给调用函数传入实参

    bind()()

    参数:指定 this 指向的对象,后边 () 为执行符号

    Processed: 0.024, SQL: 9