返回
this——面向对象编程的核心:构建你的编程思维!
前端
2024-02-22 01:22:20
this 的基本介绍
在面向对象编程中,this 是一个非常重要的语法点。毫不夸张地说,不理解它的含义,大部分开发任务都无法完成。前一章已经提到,this 可以用在构造函数之中,表示实例对象。除此之外,this 还可以用在别的场合。
-
this 用在方法中
在方法中,this 表示当前对象。我们可以通过 this 来访问当前对象的数据和方法。例如,在下面的代码中,我们通过 this 来访问当前对象的 name 属性和 sayHello() 方法:
class Person { constructor(name) { this.name = name; } sayHello() { console.log(`Hello, my name is ${this.name}`); } } const person = new Person('John'); person.sayHello(); // 输出:Hello, my name is John
-
this 用在属性中
在属性中,this 表示当前类的实例。我们可以通过 this 来访问当前类的属性。例如,在下面的代码中,我们通过 this 来访问当前类的 name 属性:
class Person { static name = 'John'; constructor() { this.name = 'Jane'; } } const person = new Person(); console.log(person.name); // 输出:Jane
-
this 用在继承中
在继承中,this 表示父类的实例。我们可以通过 this 来访问父类的属性和方法。例如,在下面的代码中,我们通过 this 来访问父类的 name 属性和 sayHello() 方法:
class Parent { constructor(name) { this.name = name; } sayHello() { console.log(`Hello, my name is ${this.name}`); } } class Child extends Parent { constructor(name) { super(name); } } const child = new Child('John'); child.sayHello(); // 输出:Hello, my name is John
-
this 用在多态中
在多态中,this 表示子类的实例。我们可以通过 this 来访问子类的属性和方法。例如,在下面的代码中,我们通过 this 来访问子类的 name 属性和 sayHello() 方法:
class Parent { constructor(name) { this.name = name; } sayHello() { console.log(`Hello, my name is ${this.name}`); } } class Child extends Parent { constructor(name) { super(name); } sayHello() { console.log(`Hello, my name is ${this.name} and I'm a child`); } } const parent = new Parent('John'); const child = new Child('Jane'); parent.sayHello(); // 输出:Hello, my name is John child.sayHello(); // 输出:Hello, my name is Jane and I'm a child
总结
this 是面向对象编程的核心概念,理解它的含义对编程至关重要。本文深入探讨了 this 关键字在不同编程语言中的用法,并通过实例演示了其在对象创建、方法调用、属性访问、继承和多态中的应用。通过阅读本文,您将掌握 this 关键字的基本知识,并能够灵活运用它来构建自己的编程解决方案。