


Javascript object-oriented programming (1) encapsulation_js object-oriented
What’s the hardest part about learning Javascript?
I think Object is the hardest. Because the Object model of Javascript is very unique and different from other languages, it is not easy for beginners to master.
The following are my study notes. I hope it will be helpful to everyone in studying this part. I mainly referred to
the following two books:
《Object-Oriented Javascript》(Object-Oriented JavaScript)
《Javascript Advanced Programming (Second Edition)》(Professional JavaScript for Web Developers, 2nd Edition)
They are all excellent Javascript books and are recommended reading.
The note is divided into three parts. The first part today is about "Encapsulation", and the second part and the third part will discuss "Inheritance".
============================
Javascript Object-Oriented Programming (1): Encapsulation
Author: Ruan Yifeng
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. Generate the original mode of the object
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 this prototype object.
var cat1 = {}; // Create an empty object
cat1.name = "大马"; // Assign values according to the attributes of the prototype object
cat1.color = "yellow";
var cat2 = {};
cat2.name = "Ermao";
cat2.color = "Black";
Okay, this is the simplest encapsulation. 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. Improvement of the original mode
We can write a function to solve the problem of code duplication.
function Cat(name,color){
return {
in in in us in us in us in us in us in us can in us us can may may us may may may on in in: 🎜>
Copy code
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 cat prototype object can now be written like this,
Copy the code
The code is as follows:
function Cat(name,color){
this.name=name;
this.color=color;
}
We can generate it now instance object.
var cat1 = new Cat("Big Hair","Yellow ");
var cat2 = new Cat("二毛","black");
alert(cat1.name); // Big Cat
alert(cat1.color); // Yellow
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 the prototype object and the instance object.
alert(cat1 instanceof Cat); //true
Alert(cat2 instanceof Cat); //true
4. Problems with the 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 = "Feline";
this.eat = function(){ alert("Eat mice");};
}
Use the same method to generate an instance:
var cat1 = new Cat("Big Hair","Yellow");
var cat2 = new Cat ("Er Hair","Black" ");
alert(cat1.type); // Cats
cat1.eat(); // Eating mice
On the surface there seems to be no problem, but in fact Do, there is a big drawback. 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 = "Feline";
Cat.prototype.eat = function(){alert("Eat Mouse")};
Then, generate the instance.
var cat1 = new Cat("Big Hair","Yellow ");
var cat2 = new Cat("二毛","黑");
alert(cat1.type); // Cats
cat1.eat(); // Eat mice
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. Prototype mode verification method
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
in operator can be used to determine whether an instance contains An attribute, whether local 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]); }
Not finished yet, please continue reading the second part of this series " Constructor Inheritance " and the third part "Inheritance of non-constructor functions ".
(End)

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 Go language to implement object-oriented event-driven programming Introduction: The object-oriented programming paradigm is widely used in software development, and event-driven programming is a common programming model that realizes the program flow through the triggering and processing of events. control. This article will introduce how to implement object-oriented event-driven programming using Go language and provide code examples. 1. The concept of event-driven programming Event-driven programming is a programming model based on events and messages, which transfers the flow control of the program to the triggering and processing of events. in event driven

The @JsonIdentityInfo annotation is used when an object has a parent-child relationship in the Jackson library. The @JsonIdentityInfo annotation is used to indicate object identity during serialization and deserialization. ObjectIdGenerators.PropertyGenerator is an abstract placeholder class used to represent situations where the object identifier to be used comes from a POJO property. Syntax@Target(value={ANNOTATION_TYPE,TYPE,FIELD,METHOD,PARAMETER})@Retention(value=RUNTIME)public

Go language supports object-oriented programming through type definition and method association. It does not support traditional inheritance, but is implemented through composition. Interfaces provide consistency between types and allow abstract methods to be defined. Practical cases show how to use OOP to manage customer information, including creating, obtaining, updating and deleting customer operations.

Analyzing the Flyweight Pattern in PHP Object-Oriented Programming In object-oriented programming, design pattern is a commonly used software design method, which can improve the readability, maintainability and scalability of the code. Flyweight pattern is one of the design patterns that reduces memory overhead by sharing objects. This article will explore how to use flyweight mode in PHP to improve program performance. What is flyweight mode? Flyweight pattern is a structural design pattern whose purpose is to share the same object between different objects.

OOP best practices in PHP include naming conventions, interfaces and abstract classes, inheritance and polymorphism, and dependency injection. Practical cases include: using warehouse mode to manage data and using strategy mode to implement sorting.

The Go language supports object-oriented programming, defining objects through structs, defining methods using pointer receivers, and implementing polymorphism through interfaces. The object-oriented features provide code reuse, maintainability and encapsulation in the Go language, but there are also limitations such as the lack of traditional concepts of classes and inheritance and method signature casts.

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

C# (CSharp) is a powerful and popular object-oriented programming language that is widely used in the field of software development. During the C# development process, it is very important to understand the basic concepts and design principles of object-oriented programming (OOP). Object-oriented programming is a programming paradigm that abstracts things in the real world into objects and implements system functions through interactions between objects. In C#, classes are the basic building blocks of object-oriented programming and are used to define the properties and behavior of objects. When developing C#, there are several important design principles
