JavaScript基础知识系列:面向对象的编程

岳迪
2023-12-01

JavaScript Basics is a series that explore some core concepts that every frontend software engineer should understand. Those concepts are not only important for success in job interviews but also for a career as a developer.

“ JavaScript基础知识”系列探讨了每个前端软件工程师都应理解的一些核心概念。 这些概念不仅对于求职面试的成功至关重要,而且对于开发人员的职业也很重要。

Object-oriented programming (OOP) is one of the many programming paradigms used in the world of programming languages. Its ability to capture and represent the world in an intuitive way has earned it a great deal of popularity, to the extent that most modern languages, such as Java, JavaScript, Python, provide some level of support for it. Let’s jump right in and learn more about it using JavaScript! :)

面向对象编程(OOP)是编程语言领域中使用的众多编程范例之一。 它以直观的方式捕获和表示世界的能力赢得了极大的欢迎,在某种程度上,大多数现代语言(例如Java,JavaScript,Python)为此提供了一定程度的支持。 让我们直接进入并使用JavaScript进一步了解它! :)

Object-oriented programming is the process of using ‘objects’ as the basis for building applications. OOP aims to describe real-life objects, like a car, house, human, or cat, using 4 main concepts:

面向对象的编程是使用“对象”作为构建应用程序基础的过程。 OOP旨在使用以下4个主要概念来描述现实生活中的对象,例如汽车,房屋,人或猫:

  • Encapsulation

    封装形式
  • Polymorphism

    多态性
  • Inheritance

    遗产
  • Abstraction

    抽象化

Encapsulation

封装形式

It’s the fact of bundling all the contents of the object into a ‘capsule’ that is referred to as a class. The class contains variables and functions, called methods, that allow it to perform specific tasks. You can think of it as a toolbox; the toolbox allows you to put all related tools in one place. Of course, you wouldn’t place your toothbrush in there, right? Only household tools are supposed to go in that box. For example, you could have a Car class that has a variable for the brand name. In JavaScript, classes are defined using the following notation:

这是将对象的所有内容捆绑到称为“ ”的“胶囊”中的事实。 该类包含称为方法的变量和函数,使它们可以执行特定任务。 您可以将其视为工具箱。 该工具箱使您可以将所有相关工具放在一个地方 。 当然,您不会将牙刷放在那里,对吗? 该盒子中只能放入家用工具。 例如,您可能有一个带有品牌变量的Car类。 在JavaScript中,使用以下符号定义类:

class ClassName {    //Definition goes here}

The convention is to use an uppercase letter for the class name and camel-casing if it consists of multiple words. For instance, ‘car show’ would become class CarShow. Let’s go ahead and define a Car class:

约定是对类名使用大写字母,如果由多个单词组成,则使用骆驼式大写字母。 例如,“ 汽车展”将变成class CarShow 。 让我们继续定义Car类:

class Car {}

This class will allow us to create copies of it later, called instances of the class. When defining a class, you want to use something called a constructor to assign values to its instances. In our case, we can use a constructor to assign a brand name to the car object.

此类将使我们以后可以创建其副本,称为实例 班上的 在定义一个类时,您想使用一种称为构造函数的东西来为其实例分配值。 在我们的例子中,我们可以使用构造函数为汽车对象分配品牌名称。

class Car {        constructor(brand) {             this.carname = brand;       }}

The keyword this represents an instance of the car and ‘carname’ is called a property of the car. Now, that we have defined our Car class, we can create an instance (a copy) of it and give it a name.

关键字this代表汽车的实例,“ carname”被称为汽车的属性 。 现在,我们已经定义了Car类,我们可以为其创建一个实例(副本)并为其命名。

let myCar = new Car("Toyota");   //Create a Car instanceconsole.log(myCar.carname);      //Output it to the console

Output: Toyota

输出: Toyota

Encapsulation enables us to create a single Car class with any number of properties and make as many copies of it as we’d like! Isn’t that amazing! Whenever we need to change a property and have it affect our instances, we can simply change it in the class definition itself without having to change every single one of them! Amazing!

封装使我们能够创建具有任意数量的属性的单个Car类,并根据需要复制任意数量的Car类! 那不是太神奇了! 每当我们需要更改一个属性并使它影响我们的实例时,我们都可以在类定义本身中简单地更改它,而不必更改每个属性! 惊人!

We can further enhance our class by giving it a function that represents the sound it makes.

我们可以通过给它一个表示其声音的函数来进一步增强我们的类。

class Car {    constructor(brand) {           this.carname = brand;     }     sound(){            return "Vroom!!!"     }}

We can then log it out: console.log(myCar.sound())

然后我们可以注销它: console.log(myCar.sound())

Output: Vroom!!!

输出: Vroom!!!

Awesome! 

太棒了! 

多态性 (Polymorphism)

The word polymorphism literally means ‘existing in many forms’, from the Greek poly (many) and morphe (form). This concept means that the methods in a class can have multiple forms. In our example, our sound method could be redefined to take an argument for the type of sound it makes.

“多态”一词的字面意思是“以多种形式存在”,源于希腊语“ poly (许多)”和“ morphe (形式)”。 这个概念意味着类中的方法可以具有多种形式。 在我们的示例中,我们的sound方法可以重新定义为采用其声音类型的参数。

class Car {      constructor(brand) {           this.carname = brand;      }      sound(){            return "Vroom!!!"    }      sound(honk){            return honk + "!!!"     }}

Let create an instance and use our new version of this method:

让我们创建一个实例,并使用此方法的新版本:

let myCar = new Car("Toyota")console.log(myCar.sound("peepeeep"))

Output: peepeeep!!!

输出: peepeeep!!!

The second method is said to override the first one. Although the example is trivial, the point is that we can create a different version of a method for specific purposes. That’s polymorphism!

据说第二种方法可以覆盖第一种方法。 尽管该示例很简单,但关键是我们可以为特定目的创建不同版本的方法。 那是多态!

遗产 (Inheritance)

One of the coolest features of OOP is that classes can inherit from others in the same way that a child inherits the traits of the parents. The child class can not only inherit all the properties and methods of the parent class but also, add to, or extend them!

OOP的最酷的功能之一就是类可以从其他类继承,就像孩子继承父母的特征一样。 子类不仅可以继承父类的所有属性和方法,还可以添加或扩展它们!

class Parent {        constructor(firstname, lastname, haircolor) {            this.firstName = firstname;            this.lastName = lastname            this.hairColor = haircolor         }       hairColor(){            return this.hairColor       }}

In JavaScript, each object has a link to another object called its prototype. In addition, almost all objects are instances of a built-in called Object. In other words, practically all JS objects inherit from its native Object class. The properties of a parent class can be accessed through its prototype.

在JavaScript中,每个对象都有一个链接到另一个称为其原型的对象。 另外,几乎所有对象都是内置对象(称为对象)的实例。 换句话说,几乎所有JS对象都从其本地Object类继承。 可以通过其原型访问父类的属性。

抽象化 (Abstraction)

Abstraction is the fact of hiding the code from the user and only giving them access to essential parts of the code. It can be compared to reading the blogs on this website. Behind the scenes there are hundreds of lines of codes that come together to display this page, it hides them because they’re not essential for reading this blog. Another example is that of a car, its outer splendor hides the engine, battery, axles, etc. We only think of a car as a single object, although it is made up of several parts. Similarly, with abstraction, you can have a cat object that has variables called meow, purr, and bite. You can don’t need to know about those details in order to use it.

抽象是向用户隐藏代码,并仅允许他们访问代码的基本部分的事实。 可以与阅读本网站上的博客进行比较。 在幕后有数百行代码组合在一起来显示此页面,它被隐藏了,因为它们对于阅读此博客不是必不可少的。 另一个例子是汽车,它的外部光彩掩盖了引擎,电池,车轴等。尽管它由多个部分组成,但我们仅将汽车视为单个对象。 同样,通过抽象,您可以拥有一个cat对象,该对象的变量名为meow,purrbite 。 您无需了解这些详细信息即可使用它。

翻译自: https://medium.com/@joseph.pyram/object-oriented-programming-54d26e2d484c

 类似资料: