就业培训     下载中心     Wiki     联络
登录   注册

Log
  1. 首页
  2. 学习 Web 开发
  3. JavaScript — Dynamic client-side scripting
  4. 引入 JavaScript 对象
  5. Object-oriented programming

内容表

  • Classes and instances
  • 继承
  • Encapsulation
  • OOP and JavaScript
  • 摘要
  • In this module

Object-oriented programming

  • 上一
  • Overview: Objects
  • 下一

Object-oriented programming (OOP) is a programming paradigm fundamental to many programming languages, including Java and C++. In this article we'll give an overview of the basic concepts of OOP. We'll describe three main concepts: classes and instances , 继承 ,和 encapsulation . For now we'll describe these concepts without reference to JavaScript in particular, so all the examples given are given in pseudocode .

注意: To be precise, the features described here are features of a particular style of OOP called class-based or "classical" OOP. When people talk about OOP, this is generally the type they mean.

After that we'll look at how in JavaScript constructors and the prototype chain relate to these OOP concepts, and how they differ. Then in the next article we'll look at some additional features of JavaScript that make it easier to implement object-oriented programs.

Prerequisites: Understanding JavaScript functions, familiarity with JavaScript basics (见 第一步 and Building blocks ), and OOJS basics (see Introduction to objects and 对象原型 ).
Objective: To understand the basic concepts of class-based object-oriented programming.

Object-oriented programming is about modeling a system as a collection of objects, which each represent some particular aspect of the system. Objects contain both functions (or methods) and data. An object provides a public interface to other code that wants to use it, but it maintains its own private internal state: this means that other parts of the system don't have to care about what is going on inside the object.

Classes and instances

In OOP, when we model a problem in terms of objects we create abstract definitions representing the types of object we want to have in our system. For example, if we were modeling a school, we might want to have objects representing professors. Every professor has some properties in common: they all have a name and a subject that they teach. Also, every professor can do certain things: for example, they can all grade a paper, and they can introduce themselves to their students at the start of the year.

So Professor could be a class in our system, and the definition of the class lists the data and methods that every professor has.

So in pseudocode a Professor class could be written like this:

class Professor
    properties
        名称
        teaches
    方法
        grade(paper)
        introduceSelf()
								

This defines a Professor class with:

  • two data properties: 名称 and teaches
  • two methods: grade() to grade a paper, and introduceSelf() to introduce themselves.

On its own, a class doesn't do anything. It's a kind of template for creating concrete objects of that type. Each concrete professor we create is called an 实例 的 Professor class. The process of creating an instance is performed by a special function called a 构造函数 . We pass the constructor values for any internal state that we want to initialize in the new instance.

Generally, the constructor is written out as part of the class definition, and it usually has the same name as the class itself:

class Professor
    properties
        名称
        teaches
    构造函数
        Professor(name, teaches)
    方法
        grade(paper)
        introduceSelf()
								

This constructor takes two parameters so we can initialize the 名称 and teaches properties when we create a new concrete professor.

Now we have a constructor we can create some professors. Programming languages often use the keyword new to signal that a constructor is being called.

walsh = new Professor('Walsh', 'Psychology')
lillian = new Professor('Lillian', 'Poetry')
walsh.teaches  // 'Psychology'
walsh.introduceSelf()  // 'My name is Professor Walsh, and I will be your Psychology professor'
lillian.teaches  // 'Poetry'
lillian.introduceSelf()  // 'My name is Professor Lillian, and I will be your Poetry professor'

								

This creates two objects, both instances of the Professor 类。

继承

Suppose in our school we also want to represent students. Unlike professors, students can't grade papers, don't teach a particular subject, and belong to a particular year.

However, students do have a name and might also want to introduce themselves. So we might write out the definition of a student class like this:

class Student
    properties
        名称
        year
    构造函数
        Student(name, year)
    方法
        introduceSelf()
								

It would be helpful if we could represent the fact that students and professors share some properties: or more accurately, the fact that at some level they are the same kind of thing . 继承 lets us do this.

We start by observing that students and professors are both people, and people have names and want to introduce themselves. We can then model that by defining a new class Person , where we define all the common properties of people. Then Professor and Student can both derive from Person , adding their extra properties:

class Person
    properties
        名称
    构造函数
        Person(name)
    方法
        introduceSelf()
class Professor : extends Person
    properties
        teaches
    构造函数
        Professor(name, teaches)
    方法
        grade(paper)
        introduceSelf()
class Student : extends Person
    properties
        year
    构造函数
        Student(name, year)
    方法
        introduceSelf()
								

In this case we would say that Person 是 superclass or parent class of both Professor and Student . Conversely Professor and Student are 子类 or child classes of Person .

You might notice that introduceSelf() is defined in all three classes. The reason is that while all people want to introduce themselves, the way they do it is different:

walsh = new Professor('Walsh', 'Psychology')
walsh.introduceSelf()  // 'My name is Professor Walsh, and I will be your Psychology professor'
summers = new Student('Summers', 1)
summers.introduceSelf() // 'My name is Summers, and I'm in the first year'

								

We might have a default implementation of introduceSelf() for people who aren't students or professors:

pratt = new Person('Pratt')
pratt.introduceSelf() // 'My name is Pratt'

								

This feature - when a method has the same name, but a different implementation in different classes - is called polymorphism . When a method in a subclass replaces the implementation of the version in the superclass, we say that the subclass overrides the version in the superclass.

Encapsulation

Objects provide an interface to other code that wants to use them, but maintain their own internal state. The object's internal state is kept private , meaning that it can only be accessed by the object's own methods, not from other objects. Keeping an object's internal state private, and in general making a clear division between its public interface and its private internal state, is called encapsulation .

This is a useful feature because it enables the programmer to change the internal implementation of an object without having to find and update all the code that uses it: it creates a kind of firewall between this object and the rest of the system.

For example, suppose students are allowed to study archery if they are in the second year or above. We could implement this just by exposing the student's year property, and other code could examine that to decide whether the student can take the course:

if (student.year > 1) {
    // allow the student into the class
}

								

The problem is, if we decide to change the criteria for allowing students to study archery - for example by also requiring the parent or guardian to give their permission - we'd need to update every place in our system that performs this test. It would be better to have a canStudyArchery() method on Student objects, that implements the logic in one place:

class Student : extends Person
    properties
       year
    构造函数
        Student(name, year)
    方法
       introduceSelf()
       canStudyArchery() { return this.year < 1 }
								
if (student.canStudyArchery()) {
    // allow the student into the class
}

								

That way, if we want to change the rules about studying archery, we only have to update the Student class, and all the code using it will still work.

In many OOP languages, we can prevent other code from accessing an object's internal state by marking some properties as private . This will generate an error if code outside the object tries to access them:

class Student : extends Person
    properties
       private year
    构造函数
        Student(name, year)
    方法
       introduceSelf()
       canStudyArchery() { return this.year < 1 }
student = new Student('Weber', 1)
student.year // error: 'year' is a private property of Student
								

In languages that don't enforce access like this, programmers use naming conventions, such as starting the name with an underscore, to indicate that the property should be considered private.

OOP and JavaScript

In this article we've described some of the basic features of class-based, sometimes referred to as "classical" object-oriented programming, as implemented in languages like Java and C++.

In the previous two articles we looked at a couple of core JavaScript features: constructors and prototypes . These features certainly have some relation to some of the OOP concepts described above.

  • constructors in JavaScript provide us with something like a class definition, enabling us to define the "shape" of an object, including any methods it contains, in a single place. But prototypes can be used here, too. For example, if a method is defined on a constructor's prototype property, then all objects created using that constructor get that method via their prototype, and we don't need to define it in the constructor.
  • the prototype chain seems like a natural way to implement inheritance. For example, if we can have a Student object whose prototype is Person , then it can inherit 名称 and override introduceSelf() .

But it's worth understanding the differences between these features and the "classical" OOP concepts described above. We'll highlight a couple of them here.

First, in class-based OOP, classes and objects are two separate constructs, and objects are always created as instances of classes. Also, there is a distinction between the feature used to define a class (the class syntax itself) and the feature used to instantiate an object (a constructor). In JavaScript, we can and often do create objects without any separate class definition, either using a function or an object literal. This can make working with objects much more lightweight than it is in classical OOP.

Second, although a prototype chain looks like an inheritance hierarchy and behaves like it in some ways, it's different in others. When a subclass is instantiated, a single object is created which combines properties defined in the subclass with properties defined further up the hierarchy. With prototyping, each level of the hierarchy is represented by a separate object, and they are linked together via the __proto__ property. The prototype chain's behavior is less like inheritance and more like delegation . Delegation is a programming pattern where an object, when asked to perform a task, can perform the task itself or ask another object (its delegate ) to perform the task on its behalf. In many ways delegation is a more flexible way of combining objects than inheritance (for one thing, it's possible to change or completely replace the delegate at run time).

That said, constructors and prototypes can be used to implement class-based OOP patterns in JavaScript. But using them directly to implement features like inheritance is tricky, so JavaScript provides extra features, layered on top of the prototype model, that map more directly to the concepts of class-based OOP. These extra features are the subject of the next article.

摘要

This article has described the basic features of class-based object oriented programming, and briefly looked at how JavaScript constructors and prototypes compare with these concepts.

In the next article we'll look at the features JavaScript provides to support class-based object-oriented programming.

  • 上一
  • Overview: Objects
  • 下一

In this module

  • Object basics
  • 对象原型
  • Object-oriented programming concepts
  • Classes in JavaScript
  • Working with JSON data
  • Object building practice
  • Adding features to our bouncing balls demo

发现此页面有问题吗?

  • 编辑在 GitHub
  • 源在 GitHub
  • Report a problem with this content on GitHub
  • 想要自己修复问题吗?见 我们的贡献指南 .

最后修改: Jan 28, 2022 , 由 MDN 贡献者

相关话题

  1. Complete beginners start here!
  2. Web 快速入门
    1. Getting started with the Web overview
    2. 安装基本软件
    3. What will your website look like?
    4. 处理文件
    5. HTML 基础
    6. CSS 基础
    7. JavaScript 基础
    8. 发布您的网站
    9. How the Web works
  3. HTML — Structuring the Web
  4. HTML 介绍
    1. Introduction to HTML overview
    2. Getting started with HTML
    3. What's in the head? Metadata in HTML
    4. HTML text fundamentals
    5. Creating hyperlinks
    6. Advanced text formatting
    7. Document and website structure
    8. Debugging HTML
    9. Assessment: Marking up a letter
    10. Assessment: Structuring a page of content
  5. 多媒体和嵌入
    1. Multimedia and embedding overview
    2. Images in HTML
    3. Video and audio content
    4. From object to iframe — other embedding technologies
    5. Adding vector graphics to the Web
    6. Responsive images
    7. Assessment: Mozilla splash page
  6. HTML 表格
    1. HTML tables overview
    2. HTML table basics
    3. HTML Table advanced features and accessibility
    4. Assessment: Structuring planet data
  7. CSS — Styling the Web
  8. CSS 第一步
    1. CSS first steps overview
    2. What is CSS?
    3. Getting started with CSS
    4. How CSS is structured
    5. How CSS works
    6. Using your new knowledge
  9. CSS 构建块
    1. CSS building blocks overview
    2. Cascade and inheritance
    3. CSS 选择器
    4. The box model
    5. Backgrounds and borders
    6. Handling different text directions
    7. Overflowing content
    8. Values and units
    9. Sizing items in CSS
    10. Images, media, and form elements
    11. Styling tables
    12. Debugging CSS
    13. Organizing your CSS
  10. 样式化文本
    1. Styling text overview
    2. Fundamental text and font styling
    3. Styling lists
    4. Styling links
    5. Web fonts
    6. Assessment: Typesetting a community school homepage
  11. CSS 布局
    1. CSS layout overview
    2. Introduction to CSS layout
    3. Normal Flow
    4. Flexbox
    5. Grids
    6. Floats
    7. 位置
    8. Multiple-column Layout
    9. Responsive design
    10. Beginner's guide to media queries
    11. Legacy Layout Methods
    12. Supporting Older Browsers
    13. Fundamental Layout Comprehension
  12. JavaScript — Dynamic client-side scripting
  13. JavaScript 第一步
    1. JavaScript first steps overview
    2. What is JavaScript?
    3. A first splash into JavaScript
    4. What went wrong? Troubleshooting JavaScript
    5. Storing the information you need — Variables
    6. Basic math in JavaScript — Numbers and operators
    7. Handling text — Strings in JavaScript
    8. Useful string methods
    9. 数组
    10. Assessment: Silly story generator
  14. JavaScript 构建块
    1. JavaScript building blocks overview
    2. Making decisions in your code — Conditionals
    3. Looping code
    4. Functions — Reusable blocks of code
    5. Build your own function
    6. Function return values
    7. 事件介绍
    8. Assessment: Image gallery
  15. 引入 JavaScript 对象
    1. Introducing JavaScript objects overview
    2. Object basics
    3. 对象原型
    4. Object-oriented programming concepts
    5. Classes in JavaScript
    6. Working with JSON data
    7. Object building practice
    8. Assessment: Adding features to our bouncing balls demo
  16. 异步 JavaScript
    1. Asynchronous JavaScript overview
    2. General asynchronous programming concepts
    3. Introducing asynchronous JavaScript
    4. Cooperative asynchronous Java​Script: Timeouts and intervals
    5. Graceful asynchronous programming with Promises
    6. Making asynchronous programming easier with async and await
    7. Choosing the right approach
  17. 客户端侧 Web API
    1. 客户端侧 Web API
    2. Introduction to web APIs
    3. Manipulating documents
    4. Fetching data from the server
    5. Third party APIs
    6. Drawing graphics
    7. Video and audio APIs
    8. Client-side storage
  18. Web forms — Working with user data
  19. Core forms learning pathway
    1. Web forms overview
    2. Your first form
    3. How to structure a web form
    4. Basic native form controls
    5. The HTML5 input types
    6. Other form controls
    7. Styling web forms
    8. Advanced form styling
    9. UI pseudo-classes
    10. Client-side form validation
    11. Sending form data
  20. Advanced forms articles
    1. How to build custom form controls
    2. Sending forms through JavaScript
    3. CSS property compatibility table for form controls
  21. Accessibility — Make the web usable by everyone
  22. Accessibility guides
    1. Accessibility overview
    2. What is accessibility?
    3. HTML: A good basis for accessibility
    4. CSS and JavaScript accessibility best practices
    5. WAI-ARIA basics
    6. Accessible multimedia
    7. Mobile accessibility
  23. Accessibility assessment
    1. Assessment: Accessibility troubleshooting
  24. Tools and testing
  25. Client-side web development tools
    1. Client-side web development tools index
    2. Client-side tooling overview
    3. Command line crash course
    4. Package management basics
    5. Introducing a complete toolchain
    6. Deploying our app
  26. Introduction to client-side frameworks
    1. Client-side frameworks overview
    2. Framework main features
  27. React
    1. Getting started with React
    2. Beginning our React todo list
    3. Componentizing our React app
    4. React interactivity: Events and state
    5. React interactivity: Editing, filtering, conditional rendering
    6. Accessibility in React
    7. React resources
  28. Ember
    1. Getting started with Ember
    2. Ember app structure and componentization
    3. Ember interactivity: Events, classes and state
    4. Ember Interactivity: Footer functionality, conditional rendering
    5. Routing in Ember
    6. Ember resources and troubleshooting
  29. Vue
    1. Getting started with Vue
    2. Creating our first Vue component
    3. Rendering a list of Vue components
    4. Adding a new todo form: Vue events, methods, and models
    5. Styling Vue components with CSS
    6. Using Vue computed properties
    7. Vue conditional rendering: editing existing todos
    8. Focus management with Vue refs
    9. Vue resources
  30. Svelte
    1. Getting started with Svelte
    2. Starting our Svelte Todo list app
    3. Dynamic behavior in Svelte: working with variables and props
    4. Componentizing our Svelte app
    5. Advanced Svelte: Reactivity, lifecycle, accessibility
    6. Working with Svelte stores
    7. TypeScript support in Svelte
    8. Deployment and next steps
  31. Angular
    1. Getting started with Angular
    2. Beginning our Angular todo list app
    3. Styling our Angular app
    4. Creating an item component
    5. Filtering our to-do items
    6. Building Angular applications and further resources
  32. Git and GitHub
    1. Git and GitHub overview
    2. Hello World
    3. Git Handbook
    4. Forking Projects
    5. About pull requests
    6. Mastering Issues
  33. Cross browser testing
    1. Cross browser testing overview
    2. Introduction to cross browser testing
    3. Strategies for carrying out testing
    4. Handling common HTML and CSS problems
    5. Handling common JavaScript problems
    6. Handling common accessibility problems
    7. Implementing feature detection
    8. Introduction to automated testing
    9. Setting up your own test automation environment
  34. Server-side website programming
  35. 第一步
    1. First steps overview
    2. Introduction to the server-side
    3. Client-Server overview
    4. Server-side web frameworks
    5. Website security
  36. Django Web 框架 (Python)
    1. Django web framework (Python) overview
    2. 介绍
    3. 设置开发环境
    4. Tutorial: The Local Library website
    5. Tutorial Part 2: Creating a skeleton website
    6. Tutorial Part 3: Using models
    7. Tutorial Part 4: Django admin site
    8. Tutorial Part 5: Creating our home page
    9. Tutorial Part 6: Generic list and detail views
    10. Tutorial Part 7: Sessions framework
    11. Tutorial Part 8: User authentication and permissions
    12. Tutorial Part 9: Working with forms
    13. Tutorial Part 10: Testing a Django web application
    14. Tutorial Part 11: Deploying Django to production
    15. Web application security
    16. Assessment: DIY mini blog
  37. Express Web Framework (node.js/JavaScript)
    1. Express Web Framework (Node.js/JavaScript) overview
    2. Express/Node introduction
    3. Setting up a Node (Express) development environment
    4. Express tutorial: The Local Library website
    5. Express Tutorial Part 2: Creating a skeleton website
    6. Express Tutorial Part 3: Using a database (with Mongoose)
    7. Express Tutorial Part 4: Routes and controllers
    8. Express Tutorial Part 5: Displaying library data
    9. Express Tutorial Part 6: Working with forms
    10. Express Tutorial Part 7: Deploying to production
  38. Further resources
  39. Common questions
    1. HTML questions
    2. CSS questions
    3. JavaScript questions
    4. Web mechanics
    5. Tools and setup
    6. Design and accessibility

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1