search
HomeWeb Front-endJS TutorialThe application of object-oriented programming ideas in JavaScript Part _js object-oriented

In fact, object-oriented thinking is independent of programming languages. For example, in C#, in a static method of a static class, a series of static functions are called according to procedural development. It is difficult to say that this is object-oriented programming. On the contrary, it is like Excellent JavaScript libraries such as jquery and extjs embody object-oriented design ideas everywhere. This article does not intend to discuss whether JavaScript can be regarded as an object-oriented programming language. This issue is something that people who value Chinese-style exams should pay attention to. I will just briefly explain how to use object-oriented programming ideas in JavaScript.
Object-oriented must first have objects. Creating an object in javascript is very simple:

Copy code The code is as follows:

var o= {};

This creates an object, and we can easily add properties and methods to this object:
Copy code The code is as follows:

o.name="object name";
o.showName=function(){
alert(o.name);
}

However, most people are still used to putting the properties and methods of an object inside a pair of {} that defines the object:
Copy code The code is as follows:

var o = {
name: "object name",
showName: function() {
alert(o.name);
}
}

There are two ways to access properties and methods, the first one:
Copy code The code is as follows:

alert(o.name);
o.showName();

This way of writing is very common, and it is also the same way to call the properties and methods of objects in C#. There is also a special one in JavaScript, which uses the name of the attribute or method as an index to access:
Copy code The code is as follows :

alert(o["name"]);
o["showName"]();

This seems to be a bit like Kong Yiji's "fennel" There are several ways to write the word "fennel". In fact, few people use indexes to call the properties or methods of objects.
In addition to our custom properties and methods, our object also has a constructor property and toString() and other methods. These properties and methods come from the Object built-in object, and all objects will have these properties and methods. The constructor attribute points to the constructor that constructed the object. We did not use the constructor to create the object. In fact, the js interpreter will use the Object constructor. If we define the constructor ourselves, we can create objects through the constructor, so that the created objects have the same properties and methods, which starts to feel a bit object-oriented. Okay, let’s start with a simple example to see how to create a constructor:
Copy the code The code is as follows:

function Person(name, sex, age) {
this.name = name;
this.sex = sex;
this.age = age;
this.showInfo = function() {
alert("Name: " this.name " Gender: " this.sex " Age: " this.age);
}
}

us A constructor named Person is defined. The constructor has three attributes and one method. It is very simple to generate an object and call the method through the constructor:
Copy Code The code is as follows:

var zhangsan = new Person("Zhang San", "Male", 18);
zhangsan.showInfo();

After running, we can see a dialog box pop up, showing the information of the person named Zhang San:

We can also look at the constructor property of the object. See if the constructor of zhangsan is the Person we defined:
Copy the code The code is as follows:

alert(zhangsan.constructor);

The result is as shown in the figure:

As you can see, it is our Person constructor.
However, there is still a problem here. Every time we construct an object, memory space will be allocated in memory for properties and methods. In fact, all objects can use the same method, and there is no need to have multiple methods. copy, which is a waste of memory space. Now that we are aware of this problem, let's think about how to solve it. A natural idea is that since we only want to allocate memory space for the method once, we can set a value to identify whether the memory space of the method has been allocated. Following this idea, we will make the following modifications to the constructor:
Copy code The code is as follows:

function Person(name, sex, age) {
this. name = name;
this.sex = sex;
this.age = age;
if (typeof Person._initialized == "undefined") {
this.showInfo = function() {
alert("Name: " this.name " Gender: " this.sex " Age: " this.age);
}
Person._initialized = true;
}
}

Here, we use a member _initialized to indicate whether memory space has been allocated for the method. When the first object is constructed, _initialized is not defined, so our judgment statement is true. At this time, the method is defined and memory space is allocated, and then the value of _initialized is set to true to indicate the method. Memory space has been allocated. When the second object is constructed, no judgment will be entered, so memory space will not be allocated again. There seems to be no problem. Run it and see that Zhang San's information is still displayed normally. Although it's not hard work, I solved a small problem, so let's celebrate. Let's have a plate of twice-cooked pork. I want to enjoy it. Before the meal started, a girl named Li Si also wanted her personal information to pop up on the computer. OK, it’s very simple. Just construct an object and call the showInfo method:
Copy the code The code is as follows:

var lisi = new Person("李思", "女", 28);
lisi.showInfo();

In order to take care of MM, I also put this paragraph Put it in front of Zhang San. MM's information is displayed correctly, but Zhang San's information is missing. This time Zhang San was not happy. It was okay to be ranked behind MM, but he still had to have a name. This is hard on me as a programmer. It seems that I can’t eat the twice-cooked pork. Let’s fix the bug first. Open firebug, and after seeing the MM information displayed, an error occurs. The prompt is: zhangsan.showInfo is not a function. Set a breakpoint and take a look. After constructing the zhangsi object, we found that there is no showInfo method. It turns out that although there is only one showInfo method, it exists in the first object and cannot be accessed by the second object. So, how can we make objects generated by the same constructor share the same function? The prototype in javascript provides us with this function. According to the JavaScript specification, each constructor has a prototype attribute for inheritance and attribute sharing. Our showInfo method can also be viewed as a property that points to a reference to a function. Now we use prototype to make our methods shareable. The code change is very simple. Just change this.showInfo to Person.prototype.showInfo. The code after the change is as follows:
Copy code The code is as follows:

function Person(name, sex, age) {
this.name = name;
this .sex = sex;
this.age = age;
if (typeof Person._initialized == "undefined") {
Person.prototype.showInfo = function() {
alert("Name : " this.name " Gender: " this.sex " Age: " this.age);
}
Person._initialized = true;
}
}

Use this constructor to generate two objects:
Copy code The code is as follows:

var lisi = new Person("李Si", "Female", 28);
lisi.showInfo();
var zhangsan = new Person("Zhang San", "Male", 18);
zhangsan .showInfo();

After running, the information of John Si will be displayed first, and then the information of Zhang San. Now both of us are satisfied, but unfortunately my twice-cooked pork is already cold.
Statement
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
Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment