search
HomeWeb Front-endJS TutorialOne 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:

Copy the code The code is 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:
Copy code The code is as follows:

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:
Copy code 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:
Copy the code The code is as follows:

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:
Copy the code The code is as follows:

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:
Copy code The code is as follows:

(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.
Copy code The code is as follows:

(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.
Copy code The code is as follows:

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:
Copy the code The code is as follows:

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.
Copy code The code is as follows:

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:
Copy code The code is as follows:

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.
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: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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 Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment