返回

this:和对象亲密接触

前端

题外话:一个人牛逼究竟能到什么程度?

我认识一个牛逼的程序员,他牛逼到什么程度呢?他可以用this这个简单的概念写出一篇万字长文,还能做到深入浅出,妙趣横生。

他告诉我,this其实就是对象的一个指针,指向当前正在执行代码的对象。当我们在对象内部调用方法时,this就指向这个对象本身。如果我们直接调用函数,那this就指向window对象。

比如,我们有一个对象叫做person,它有两个方法,一个叫做sayHello,另一个叫做sayGoodbye。

const person = {
  name: "John",
  sayHello: function () {
    console.log(`Hello, my name is ${this.name}!`);
  },
  sayGoodbye: function () {
    console.log(`Goodbye, my name is ${this.name}!`);
  },
};

person.sayHello(); // 输出: Hello, my name is John!
person.sayGoodbye(); // 输出: Goodbye, my name is John!

在这个例子中,当我们调用person.sayHello()时,this就指向person对象,所以console.log()会输出"Hello, my name is John!"。同样的,当我们调用person.sayGoodbye()时,this也指向person对象,所以console.log()会输出"Goodbye, my name is John!"。

但是,如果我们直接调用sayHello()或sayGoodbye()函数,那就不是这样了。

sayHello(); // 输出: Hello, my name is undefined!
sayGoodbye(); // 输出: Goodbye, my name is undefined!

在这个例子中,我们没有把sayHello()或sayGoodbye()函数绑定到任何对象,所以this就指向window对象。而window对象没有name属性,所以console.log()会输出"Hello, my name is undefined!"和"Goodbye, my name is undefined!"。

这就是this的基本原理。掌握了这个原理,我们就可以解决很多跟this有关的问题。比如,我们可以用箭头函数来改变this的指向。

const person = {
  name: "John",
  sayHello: () => {
    console.log(`Hello, my name is ${this.name}!`);
  },
  sayGoodbye: () => {
    console.log(`Goodbye, my name is ${this.name}!`);
  },
};

person.sayHello(); // 输出: Hello, my name is undefined!
person.sayGoodbye(); // 输出: Goodbye, my name is undefined!

在这个例子中,我们使用箭头函数定义了sayHello()和sayGoodbye()方法。箭头函数没有自己的this,所以this就指向它所在的作用域的this。而person对象的作用域是window对象,所以this就指向window对象。因此,console.log()会输出"Hello, my name is undefined!"和"Goodbye, my name is undefined!"。

这就是this的基本用法。如果您想了解更多关于this的知识,可以参考以下文章: