普通函数可以用this吗

普通函数可以使用 this 关键字来引用当前函数被调用时所绑定的对象。

在 JavaScript 中,this 的值是在函数被调用时动态确定的,它的值取决于函数的调用方式。this 是一个特殊的关键字,它表示当前函数执行时的上下文环境。具体来说,this 的值取决于函数的调用方式,而不是函数本身的定义方式。

如果函数是作为一个对象的方法被调用,那么 this 将引用该对象。例如:

const person = {
  firstName: "John",
  lastName : "Doe",
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

person.fullName(); // 输出 "John Doe"

如果函数不是作为对象的方法被调用,那么 this 的值将是全局对象。例如:

function myFunction() {
  console.log(this);
}

myFunction(); // 输出全局对象 window 或 global(取决于环境)

此外,还可以使用 call()、apply() 和 bind() 方法来显式地设置函数中 this 的值。

猜你喜欢

转载自blog.csdn.net/liu511623/article/details/129484017