this指向

148 阅读2分钟

this

  • 在 JavaScript 中,关键字 this 用于指向当前执行上下文中的对象。它的指向是动态的,取决于代码在哪里被调用以及如何被调用。this 的值在函数执行时被确定。

示例:

1.全局作用域:

  • 在全局作用域中,this 指向全局对象,即在浏览器中是 window 对象,在 Node.js 中是 global 对象。
      console.log(this); // 输出全局对象(window 或 global)

2.函数调用:

  • 在函数中,this 的值取决于函数是如何被调用的。
  • 2.1 函数作为普通函数调用时,this 指向全局对象(非严格模式下)或 undefined(严格模式下)。
    function myFunction() {
      console.log(this);
    }

    myFunction(); // 在浏览器中输出全局对象(window),
                  // 在 Node.js 中输出 undefined(严格模式)

  • 2.2函数作为对象的方法调用时,this 指向调用该方法的对象。
        const obj = {
          myMethod() {
            console.log(this);
          }
        };

        obj.myMethod(); // 输出 obj 对象

  • 2.3 构造函数:在使用 new 关键字创建对象时,this 指向新创建的实例对象
    function MyClass() {
      console.log(this);
    }

    const myObj = new MyClass(); // 输出新创建的实例对象
  • 2.4 4. 箭头函数:箭头函数的 this 值与外部上下文保持一致,不受调用方式的影响。
        const myFunction = () => {
          console.log(this);
        };

        const obj = { name: 'John' };

        myFunction.call(obj); // 输出全局对象(window 或 global)

改变this指向

1.call

  • call 是 JavaScript 中的一个函数方法,用于调用函数并指定函数内部的 this 值。

语法:

function.call(thisArg, arg1, arg2, ...)
  • function 是要调用的函数
  • thisArg 是要设置为函数执行上下文中的 this 值的对象。
  • arg1, arg2, ... 是传递给函数的参数(可选)。

注意:

  • 当使用 call 方法调用函数时,它会立即执行函数,并将指定的 thisArg 值设置为函数内部的 this

示例:

const obj = {
msg: 'hello world'
}
function fn(x, y){
console.log(this) //  obj
console.log(this.msg) // hello world
return x + y
}
const res = fn.call(obj, 1, 2)  
console.log(res)  // 3

2.apply

  • apply 是 JavaScript 中的一个函数方法,用于调用函数并指定函数内部的 this 值和参数列表。
  • 它和 call 方法的作用类似,但参数的传递方式略有不同。

语法:

function.apply(thisArg, [argsArray])
  • function 是要调用的函数
  • thisArg 是要设置为函数执行上下文中的 this 值的对象。
  • argsArray 是一个数组或类数组对象,包含要传递给函数的参数(可选)

注意:

  • apply 方法和 call 方法的主要区别在于参数的传递方式。使用 apply 方法时,参数被放置在一个数组或类数组对象中,而不是像 call 方法一样逐个传递。

示例:

  console.log(`${greeting}, ${this.name}${punctuation}`);
}

const person = {
  name: 'Alice'
};

greet.apply(person, ['Hello', '!']); // 输出 "Hello, Alice!"

  • 通过使用 apply 方法,我们调用了 greet 函数,并将 person 对象作为 thisArg 值传递。参数 ['Hello', '!'] 被放置在一个数组中,作为第二个参数传递给 apply 方法。
  • 这样调用时,greet 函数内部的 this 指向 person 对象,greeting 参数为 'Hello'punctuation 参数为 '!',最终输出 "Hello, Alice!"。

3.bind

  • bind 是 JavaScript 中的一个函数方法,用于创建一个新函数,并将指定的 this 值绑定到该函数。
  • 它类似于 callapply 方法,但不会立即调用函数,而是返回一个绑定了指定 this 值的新函数。

语法:

function.bind(thisArg, arg1, arg2, ...)
  • thisArg 是要绑定到新函数的 this 值。
  • arg1, arg2, ... 是要在调用新函数时预先传递给新函数的参数(可选)。

注意:

  • bind 方法不会立即执行函数,而是返回一个新函数。这使得你可以将绑定后的函数保存下来,稍后再调用。

示例:

const person = {
  name: 'Alice',
  sayHello: function() {
    console.log(`Hello, ${this.name}!`);
  }
};

const greet = person.sayHello.bind(person);
greet(); // 输出 "Hello, Alice!"