


Learn Javascript object-oriented programming encapsulation_javascript skills
Javascript is an object-based language, and almost everything you encounter is an object. However, it is not a true object-oriented programming (OOP) language because there is no class in its syntax.
So, if we want to encapsulate "property" and "method" into an object, or even generate an instance object from the prototype object, what should we do?
1. Original mode of generating objects
Suppose we regard the cat as an object, which has two attributes: "name" and "color".
var Cat = { name : '', color : '' }
Now, we need to generate two instance objects based on the specification (schema) of this prototype object.
var cat1 = {}; // 创建一个空对象 cat1.name = "大毛"; // 按照原型对象的属性赋值 cat1.color = "黄色"; var cat2 = {}; cat2.name = "二毛"; cat2.color = "黑色";
Okay, this is the simplest encapsulation, encapsulating two properties into an object. However, this way of writing has two disadvantages. First, if more instances are generated, it will be very troublesome to write; second, there is no way to see the connection between the instances and the prototype.
2. Improvements to the original mode
We can write a function to solve the problem of code duplication.
function Cat(name,color){ return { name:name, color:color } }
Then generating an instance object is equivalent to calling a function:
var cat1 = Cat("大毛","黄色"); var cat2 = Cat("二毛","黑色");
The problem with this method is still that there is no intrinsic connection between cat1 and cat2, and it cannot reflect that they are instances of the same prototype object.
3. Constructor pattern
In order to solve the problem of generating instances from prototype objects, Javascript provides a constructor (Constructor) pattern.
The so-called "constructor" is actually an ordinary function, but the this variable is used internally. Using the new operator on the constructor will generate an instance, and the this variable will be bound to the instance object.
For example, the prototype object of cat can now be written like this,
function Cat(name,color){ this.name=name; this.color=color; }
We can now generate instance objects.
var cat1 = new Cat("大毛","黄色"); var cat2 = new Cat("二毛","黑色"); alert(cat1.name); // 大毛 alert(cat1.color); // 黄色
At this time, cat1 and cat2 will automatically contain a constructor attribute pointing to their constructor.
alert(cat1.constructor == Cat); //true alert(cat2.constructor == Cat); //true
Javascript also provides an instanceof operator to verify the relationship between prototype objects and instance objects.
alert(cat1 instanceof Cat); //true alert(cat2 instanceof Cat); //true
4. Problems with constructor pattern
The constructor method is easy to use, but there is a problem of wasting memory.
Please see, we now add an immutable attribute "type" (type) to the Cat object, and then add a method eat (eat mice). Then, the prototype object Cat becomes as follows:
function Cat(name,color){ this.name = name; this.color = color; this.type = "猫科动物"; this.eat = function(){alert("吃老鼠");}; }
Use the same method to generate an instance:
var cat1 = new Cat("大毛","黄色"); var cat2 = new Cat ("二毛","黑色"); alert(cat1.type); // 猫科动物 cat1.eat(); // 吃老鼠
On the surface, there seems to be no problem, but in fact, there is a big disadvantage in doing this. That is, for each instance object, the type attribute and eat() method have exactly the same content. Every time an instance is generated, it must occupy more memory for repeated content. This is neither environmentally friendly nor efficient.
alert(cat1.eat == cat2.eat); //false
Can the type attribute and eat() method be generated only once in memory, and then all instances point to that memory address? The answer is yes.
5. Prototype mode
Javascript stipulates that each constructor has a prototype attribute that points to another object. All properties and methods of this object will be inherited by the instance of the constructor.
This means that we can define those immutable properties and methods directly on the prototype object:
function Cat(name,color){ this.name = name; this.color = color; } Cat.prototype.type = "猫科动物"; Cat.prototype.eat = function(){alert("吃老鼠")};
Then, generate the instance.
var cat1 = new Cat("大毛","黄色"); var cat2 = new Cat("二毛","黑色"); alert(cat1.type); // 猫科动物 cat1.eat(); // 吃老鼠
At this time, the type attribute and eat() method of all instances are actually the same memory address, pointing to the prototype object, thus improving operating efficiency.
alert(cat1.eat == cat2.eat); //true
6. Verification method of Prototype mode
In order to cooperate with the prototype attribute, Javascript defines some auxiliary methods to help us use it. ,
6.1 isPrototypeOf()
This method is used to determine the relationship between a certain proptotype object and an instance.
alert(Cat.prototype.isPrototypeOf(cat1)); //true alert(Cat.prototype.isPrototypeOf(cat2)); //true
6.2 hasOwnProperty()
Each instance object has a hasOwnProperty() method, which is used to determine whether a certain property is a local property or a property inherited from the prototype object.
alert(cat1.hasOwnProperty("name")); // true alert(cat1.hasOwnProperty("type")); // false
6.3 in operator
The in operator can be used to determine whether an instance contains a certain attribute, whether it is a local attribute or not.
alert("name" in cat1); // true alert("type" in cat1); // true
in operator can also be used to traverse all properties of an object.
for(var prop in cat1) { alert("cat1["+prop+"]="+cat1[prop]); }
The above is all about javascript encapsulation. I hope it will be helpful to everyone's learning.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

This website reported on July 9 that the AMD Zen5 architecture "Strix" series processors will have two packaging solutions. The smaller StrixPoint will use the FP8 package, while the StrixHalo will use the FP11 package. Source: videocardz source @Olrak29_ The latest revelation is that StrixHalo’s FP11 package size is 37.5mm*45mm (1687 square millimeters), which is the same as the LGA-1700 package size of Intel’s AlderLake and RaptorLake CPUs. AMD’s latest Phoenix APU uses an FP8 packaging solution with a size of 25*40mm, which means that StrixHalo’s F
