跳到主要内容

this

this

  • 函数在执行时,JS解释器每次都会传递一个隐含的参数
  • 这个参数就叫做this
  • this会指向一个对象
    • this所指向的对象会根据函数调用方式的不同而不同
      1. 以函数的形式调用时,this指向的是window
      2. 以方法的形式调用时,this指向的是调用方法的对象
  • 通过this可以在方法中引用调用方法的对象
function fn() {
console.log(this === window);
}
fn(); // true

const obj = { name: "孙悟空" };
obj.test = fn;
obj.test(); // false

箭头函数的this

  • 箭头函数:

    • (参数) => 返回值

    • 例子:

      • 无参箭头函数:() => 返回值

      • 一个参数的:a => 返回值

      • 多个参数的:(a, b) => 返回值

      • 只有一个语句的函数:() => 返回值

      • 只返回一个对象的函数:() => ({...})

      • 有多行语句的函数:

        () => {
        ...
        return 返回值
        }
    • 箭头函数没有自己的this,它的this由它的外层作用域决定

    • 箭头函数没有自己的this指向,它的this指向上一级作用域的this,箭头函数的this和它的调用方式无关

function fn() {
console.log(this);
}
const fn2 = () => {
console.log(this);
}
const obj = {
name: "孙悟空",
fn,
fn2,
sayHello() {
console.log(this.name);
function t1() {
console.log("t1-->", this);
const t4 = () => {
console.log("t4-->", this);
}
t4(); // t4--> Window
}
const t2 = () => {
console.log("t2-->", this);
const t3 = () => {
console.log("t3-->", this);
}
t3(); // obj
}
t1(); // t1--> Window
t2(); // t2--> obj
}
}
obj.fn(); // obj
obj.fn2(); // window
obj.sayHello();

call和apply

  • 根据函数调用的方式的不同,this的值也不同
    1. 以函数形式调用,this是window
    2. 以方法形式调用,this是调用方法的对象
    3. 构造函数中,this是新建的对象
    4. 箭头函数没有自己的this,由外层作用域决定
    5. 通过call和apply调用的函数,它们的第一个参数就是函数的this
    6. 通过bind返回的函数,this由bind第一个参数决定(无法修改)
  • 调用函数除了通过 函数() 这种形式外,还可以通过其他的方式来调用函数
    • 比如,我们可以通过调用函数的call()和apply()来两个方法来调用函数
      • 函数.call()
      • 函数.apply()
    • call 和 apply 除了可以调用函数,还可以用来指定函数中的this
    • call 和 apply 的第一个参数,将会成为函数的this
    • 通过call方法调用函数,函数的实参直接在第一个参数后一个一个的列出来
    • 通过apply方法调用函数,函数的实参需要通过一个数组传递
function fn(a, b) {
console.log("函数执行了", this);
console.log(a, b);
}

const obj = { name: "孙悟空" }

fn(); // 函数执行了 Window
fn.call(obj, 1, 2); // 函数执行了 Object
fn.apply(obj, [3, 4]);

bind

  • bind() 是函数的方法,可以用来创建一个新的函数
    • bind可以为新函数绑定this
    • bind可以为新函数绑定参数
  • 箭头函数没有自身的this,它的this由外层作用域决定,也无法通过call apply 和 bind修改它的this
  • 箭头函数没有arguments
function fn(a, b, c) {
console.log("fn执行了", this); // fn执行了 {name: '孙悟空'}
console.log(a, b, c); // 10 20 30
}

const obj = { name: "孙悟空" }

const newFn = fn.bind(obj, 10);
newFn(20, 30);