


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)

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

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.

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.


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

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

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

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),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
