


One of the object-oriented Javascript (first introduction to Javascript)_js object-oriented
1. The biggest feature of Javascript is its flexibility. As a front-end developer, you can use either a functional programming style or a more complex object-oriented programming style. No matter which style you adopt, you can accomplish some very useful tasks. Therefore, Javascript is a process-oriented language and an object-oriented language, which can imitate the programming patterns and idioms of object-oriented languages. Let's use an example to illustrate: starting and stopping animations.
If you are used to functional programming style, the code will be as follows:
function startAnimation() {
//Enable animation
}
function stopAnimation() {
//Stop animation
}
This method is simple, but it cannot create animated objects that save state and only operate on internal state. Below we define a class:
var Animation = function() {
//Animation class
};
Animation.prototype.start = function() {
//Enable animation
};
Animation.prototype.stop = function() {
//Stop animation
};
/*Usage as follows*/
var anim = new Animation();
anim.start();
anim.stop() ;
If you want to encapsulate the class definition into a declaration, the code is as follows:
var Animation = function() {
//Animation class
};
Animation.prototype = {
start: function() {
//Enable animation
},
stop: function(){
//Stop animation
}
};
This way the orientation The object's programmer looks more familiar, we can try a more complex way of writing:
Function.prototype.method = function(name, fn){
this.prototype[name] = fn;
}
var Animation = function() {
//Animation class
};
Animation.method("start", function(){
//Enable animation
});
Animation.method("stop", function( ){
//Stop animation
});
We have extended a method method for the Function class to add new methods. name represents the function name, and fn represents the specific implementation of the function. Based on this writing method, we can make the function support chain calls:
Function.prototype.method = function(name, fn){
this.prototype[name] = fn;
return this;
}
var Animation = function() {
//Animation class
};
Animation.method("start", function(){
//Enable animation
}).method("stop", function() {
//Stop animation
});
So far, I have seen 5 different programming styles, with different code amounts, coding efficiency and execution performance. You can work in the programming style that best suits your current project.
2. Javascript is a weakly typed language. You don't have to specify a type when declaring a variable, but that doesn't mean there is no type. Javascript contains three basic types: boolean, numeric and string types, as well as object types and function types, and finally empty types and undefined types. Primitive types are passed by value, other types are passed by reference. The type can be changed according to variable assignment, and basic types can be converted to each other. toString() can convert a numerical or Boolean value into a string, parseInt() and parseFloat() can convert a string into a numerical value, and the double "not" operation can convert a string or numerical value into a Boolean value.
3. Javascript functions are "first-class" objects. Functions can be stored in variables, passed as arguments to other functions, passed as return values from other functions, or constructed at runtime. When dealing with functions, it brings great flexibility and strong expressive capabilities, which are the basis for building object-oriented. Anonymous functions can be created through function() {...} (without a function name, it can also be assigned to a variable). The following is an example:
(function(){
var a = 10;
var b = 5;
alert(a * b);//Return 50
})();//The function definition will be executed immediately
The reason why it can be executed immediately is because of the pair of parentheses after the function declaration. But we find that it is not entirely the case that there is nothing in the brackets.
(function(a, b){
alert (a * b);//Return 50
})(10, 5);//Equivalent to the previous one
This anonymous function is equivalent to the previous one, except that the variable is not in the function It is declared inside, but passed in directly from the outside. In fact, this anonymous function can also have a return value and assign it to a variable.
var c = (function(a, b){
return a * b;//Return 50
})(10, 5);//Equivalent to the previous
alert(c);//50
Anonymous function The biggest use is to create closures. The so-called closure is a protected variable space generated by embedded functions. Since Javascript has function-level scope, that is, variables defined inside a function cannot be accessed outside the function. The function only runs in the scope in which it is defined, not in the calling scope. In this way, variables can be protected by wrapping them in anonymous functions. For example, you can create a private variable by:
var c;
(function(){
var a = 10;
var b = 5;
c = function(){
return a * b; //return 50
}
})();
c();//c can access a, b, even if it is executed outside the anonymous function
4. Javascript object is "Variable". Everything is an object (except the 3 basic types), and all objects are mutable. This means you can use some techniques that don't exist in other languages. For example, add attributes dynamically to functions.
function displayError(error){
displayError.numTimesExecuted ;
alert(error);
}
displayError.numTimesExecuted = 0;//It means that predefined classes and objects can be modified
You can use the prototype mechanism to When an instance of a class is created and then added dynamically, it is still valid for the defined object. For example:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype = {
getName: function() {
return this.name;
},
getAge: function() {
return this.age;
}
};
//First define two variables
var miracle = new Person("Miracle", 28 );
var mike = new Person("Mike", 32);
//Dynamicly add a method
Person.prototype.getGreeting = function() {
return "Hello " this.getName () "!";
};
//displayGreeting() is only valid for Miracle
miracle.displayGreeting = function() {
alert(this.getGreeting());
}
Related to the mutability of objects is reflection (also called "introspection"), which checks the properties and methods of objects at runtime and uses this information to instantiate classes and execute methods, even during development No need to know their names. With the help of these two characteristics of objects, you can completely imitate the advanced features of object-oriented languages, but remember that any object in Javascript can be modified at runtime.
5. Javascript has the talent to implement "inheritance". Here is a brief mention: Javascript inheritance includes "class" inheritance and object-based prototype inheritance. I will discuss this topic in detail in the next article.
Finally, to summarize, what are the benefits of using object-oriented and design pattern ideas to deal with a seemingly procedural language like Javascript? I have summarized the following points for your reference:
(1). Maintainability. It helps to reduce the coupling between modules, and the code in the project can be divided according to modules and functional responsibilities.
(2). Easy to communicate. For a large team, it may be possible to use design patterns in very simple terms to provide a high-level summary of the functional modules you are responsible for implementing without having to focus too much on the details of other team members.
(3). Improve performance. Exploiting patterns can reduce the amount of code sent to the client and increase the speed of program execution.
Of course, there are pros and cons. The disadvantages are:
(1). The complexity is relatively high. The cost of obtaining maintainability is a high degree of code reconstruction and modular division, which is difficult for some novices to adapt to at once.
(2). Some modes actually reduce performance. But depending on your project needs, this drag may be trivial or unacceptable.
Therefore, it is recommended that everyone learn to understand the application scenarios of design patterns. Using the right scenarios is the true application of design patterns. Blind application or use in the wrong scenario is misuse, and it is better not to use it.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.


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

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.