Home > Web Front-end > JS Tutorial > body text

Object-oriented programming in JavaScript

黄舟
Release: 2017-02-22 13:39:03
Original
1439 people have browsed it


Introduction

JavaScript is a powerful object-oriented programming language, but unlike traditional programming languages, it uses a prototype-based OOP model. As a result, its syntax is incomprehensible to most developers. In addition, JavaScript also treats functions as primary objects, which may cause greater confusion for developers who are not familiar with the language. That's why we decided to put it up front as a brief introduction, and it can also be used as a reference for object-oriented programming in JavaScript.

This document does not provide a preview of the rules of object-oriented programming, but does provide an overview of their interfaces.

Namespace

With the emergence of more and more third-party libraries, frameworks and web dependencies, namespaces are imperative in the development of JavaScript. We must try to avoid Conflict between global namespace objects and variables.

Unfortunately, JavaScript does not provide support for namespace compilation, but we can use objects to achieve the same result. In JavaScript we have many patterns for implementing namespace interfaces, but we cover nested namespaces, which is the most commonly used pattern in this field.

Nested namespaces

The nested namespace pattern uses object literals to bundle functionality with a specific name for a specific application.

We initially create a global object and assign it to a variable called MyApp.

The above syntax will check whether MyApp has been defined. If it was already defined, we simply assign it to ourselves, but instead we create an empty container to hold our functions and variables.

We can also use the same technique to create sub-namespaces. For example:

Once we start our container, we can define our functions and variables inside (the container) and call them in the global namespace without risking Risk of conflict with existing definitions.

An internal overview of naming patterns in JavaScript was introduced by Addy Osmani of Goggle in the article Essential JavaScript Namespacing Patterns. If you want to explore different modes, this would be a great place to start.

Objects

If you’ve ever written JavaScript code, you’ve already used objects. JavaScript has three types of objects:

Native objects

Native objects are part of the language specification. Native objects are available no matter what running environment they are run in. Native objects include: Array, Date, Math, parseInt, etc. To learn about all native objects, see JavaScript Built-in Object Reference

Host Objects

Unlike native objects, host objects are the environment in which JavaScript code runs. create. Different environments create different host objects. These host objects allow us to interact with them in most cases. If we write code that runs on a browser (which is one of the running environments), there will be host objects such as window, document, location, and history.

User object

User object (or implanted object) is an object defined in our code and created during runtime. There are two ways to create your own objects in JavaScript, detailed below.

Object literals

When we demonstrated the creation of a namespace earlier, we have already come into contact with object literals. Now let’s clarify the definition of an object literal: an object literal is a comma-separated list of name-value pairs enclosed in a pair of curly braces. Object literals can have variables (properties) and functions (methods). Like other objects in JavaScript, it can be used as a function parameter or as a return value.

Now define an object literal and assign it to a variable:

Add properties and methods to this object literal, and then access them in the global scope:

This looks very similar to the previous namespace, but this is no coincidence. The most typical use of literal objects is to encapsulate code in an encapsulated package to avoid conflicts with variables or objects in the global scope. It is also often used to pass configuration parameters to plugins or objects for similar reasons.

If you are familiar with design patterns, object literals are singletons to a certain extent, which is the pattern where there is only one instance. Object literals inherently do not have the ability to instantiate and inherit. Next, we have to learn about another way to create custom objects in JavaScript.

Constructor

Define constructor

Functions are first-class citizens of JavaScript, which means that all operation functions supported by other entities are supported. In the world of JavaScript, functions can be dynamically constructed at runtime, can be used as parameters, can be used as return values ​​​​of other functions, and can also be assigned to variables. Moreover, functions can also have their own properties and methods. The nature of functions in JavaScript makes them something that can be instantiated and inherited.

Let’s see how to use a constructor to create a custom object:

Creating a constructor is similar to creating a normal function, with one exception: use this Keywords define spontaneity and method. Once a function is created, instances can be created and assigned to variables using the new keyword. Each time the new keyword is used, this points to a new instance.

Constructor function instantiation is not completely different from class instantiation in traditional object-oriented programming languages, but there is a problem here that may not be easily noticed.

When using the new keyword to create a new object, the function block will be executed repeatedly, which will generate a new anonymous function to define the method each time it is run. This is like creating a new object, which causes the program to consume more memory. This problem is not noticeable in programs running on modern browsers. But as application rules expand, performance issues may occur in older browsers, computers, or low-power devices. But don't worry, there is a better way to attach the method to the constructor (it will not pollute the global environment).

Methods and prototypes

As mentioned in the previous introduction, JavaScript is a programming language based on prototypes. In JavaScript, prototypes can be used like object templates. Prototypes avoid creating redundant anonymous functions and variables when instantiating objects.

In JavaScript, prototype is a very special attribute that allows us to add new properties and methods to objects. Now rewrite the above example using the prototype:

## In this example, the sayHey method is no longer defined for each Person instance, but is defined in each instance through the prototype template Share this method.

Inheritance

Through the prototype chain, prototypes can be used for instance inheritance. Every object in JavaScript has a prototype, and the prototype is another object that also has its own prototype, and the cycle starts over and over... until the prototype of a prototype object is null - the prototype chain ends here.

When accessing a method or property, JavaScript first checks whether they are defined in the object, and if not, checks whether they are defined in the prototype. If it is not found in the prototype, it will continue to search along the prototype chain until it is found or reaches the end of the prototype chain.

Now let’s see how the code is implemented. You can start with the Person object from the previous example and create an additional object called Employee.

Now Employee has only one attribute. But since employees are also people, we want it to inherit other properties from Person. To achieve this, we can call the Person constructor in the Employee object and configure the prototype chain.

It will take some time to get used to prototypal inheritance, but this is an important concept that you must be familiar with. While the prototypal inheritance model is often considered JavaScript's weak point, it's actually more powerful than the traditional model. For example, it is almost too easy to create traditional models after mastering the prototype model.

ECMAScript 6 introduces a new set of keywords for implementing classes. Although the new design looks very close to traditional class-based development languages, they are not the same. JavaScript is still based on prototypes.

Conclusion

JavaScript has evolved over a long period of time, and during this period, a large number of developers used methods that should not have been used by today's standards. According to the introduction of ES2015, this situation is slowly starting to change, however, many developers are still stuck with some old programming methods, which hurts the relevance of their code. Understanding object-oriented programming methods and applying them to your JavaScript projects makes a lot of sense for writing sustainable code.

I hope this brief introduction will help you achieve this goal.

The above is the content of object-oriented programming in JavaScript. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template