search
HomeWeb Front-endJS TutorialJavaScript Advanced Chapter: Closures, Simulation Classes, Inheritance (5)_javascript skills

1. Closures in JavaScript
1. Let’s first understand what the scope of a function is.

2. Called object

Combination example:

Copy code The code is as follows:

function display( something)
{
function executeDisplay1()
{
document.write("I am helping the boss print:" something "
");//something that refers to an external function Parameters
}
executeDisplay1();//Function display refers to the internal function
}
display("sorry");//After execution, it is recycled by the garbage collector

3. Formation of closure

Example 1,

Copy code The code is as follows:

var obj = {};//Global object
function buyHouse(price,area)
{
return function(){return "The price you want to pay:" price*area;}; //Put the internal Function as return value
}
obj.people = buyHouse(12000,80); //Save the reference of the internal function into the people attribute of the obj object.
//This forms a closure, a simple expression: save the reference of the nested function in the global scope, whether you use the value it returns, or store it in the properties of the object.
document.write(obj.people() "
");

Example 2,
Copy Code The code is as follows:

function add()
{
var number = 0;
return function(){return number;} ;//
}
var num = add();//Now there are 4 references, right? The first one is globally created: access function, and the second one has external function (here refers to Add( ) refers to the anonymous function)
//The third one is the anonymous function (that is, the return function... refers to the local variable of Add), and the fourth one is the global object (var num).
//The object of each call to the global object is still saved in the function body, so the values ​​of local variables will be maintained.
document.write(num());

//Equivalent method
num2 = (function(){var number = 0;return function(){return number;}}) ();//Anonymous function, directly assigned to the global object
document.write(num2());

Example 3, implementing private attributes
Copy code The code is as follows:

//Use closures to implement private properties
function createProperty(o,propertyname,check)
{
var value;
o["get" propertyname] = function(){return value;};//Return an anonymous function body to the object's property
o["set" propertyname] = function(v){if(check && !check)//Check the legality of the parameters throw("The parameter is incorrect!");
else value = v; };//Return an anonymous function body Properties for the object
}
var o = {};
createProperty(o,"Age",function(x){return typeof x == "number";});//followed by An anonymous function that performs verification work and returns false if it is not a number
o.setAge(22); //Use the properties of the object
document.write(o.getAge());

//In fact, the function is saved in the properties of the global object.

2. Classes in JavaScript
Let’s also start with some basic terms!
1. Prototype

In fact, the prototype of an object is the prototype value of the constructor. All functions have a prototype attribute. When the function is created, it is automatically created and initialized. Initialize it The value is an object. This object has a property called constructor, which points back to the constructor associated with the prototype.
Copy code The code is as follows:

function PeopleHope(money,house)
{
this.money = money;
this.house = house;
}
PeopleHope.prototype.hope = function( ){document.write("I want to own money and a house");};//This is the prototype, which will be initialized into the properties of the object by the constructor.
for(var p in PeopleHope.prototype)
{
document.write("The prototype is out! t " p "
");//Output: The prototype is out ! hope
}

2. Simulation class

In fact, the "class" in Javascript is just a function. Just jump into the code!
Copy code The code is as follows:

function PeopleHope(money,house)
{
this.money = money;
this.house = house;
PeopleHope.VERSION = 0.1//Attributes of the class
PeopleHope.createLive = function(){document.write("In the leadership of the party Next, our life is very good! ");}//Class methods must be direct references to the class
}

3. Class inheritance
Copy code The code is as follows:

function CreateClass(name,version)
{
this.name = name; //Initialization Object attribute
this.version= version;
CreateClass.AUTHOR = "Frank";//Class attribute
CreateClass.SellHouse = function(){document.write("We are the leading real estate company Vanke") ;};//Class method
CreateClass.prototype.Company = "vanke";
CreateClass.prototype.HousePrice = function(){document.write("A luxury home on the top of Dameisha sold for 50 million , best-selling price! ");};
//Prototype, in fact, you may ask at this point, what is the difference between this prototype and class methods?
//Actually: For example, var o = new CreateClass("COFCO Real Estate", "Phase 1"); this in the CreateClass function is o, and together it is
//o.name = "COFCO Real Estate" ";o.version = "Issue 1";Here!
//As for what the prototype is actually doing, you can think of it as a "traitor". When you create the object o, the prototype tells the constructor to take away the initialization together
//It becomes the object o property.
}
function House(name,version,city)
{
CreateClass.apply(this,[name,version]);//Inherited constructor
this.city = city;
House.prototype.housename = "Peninsula Garden";
}
House.prototype = new CreateClass("COFCO Real Estate", "Phase II");//Get the CeateClass attribute through new, including the prototype object
//Print the prototype attribute of the function
function displayPrototype(c)
{
for(var x in c.prototype)
{
document.write(x "
");
}
}
displayPrototype(House);//Output: HousePrice Company name version
//Delete objects that are not prototypes
delete House.prototype.name; //Delete
delete House.prototype.version; //Delete
displayPrototype(House); //Output: HousePrice Company
var customers = new House("Peninsula Garden","Phase Three"," West pull teeth");
for(var t in customers)
{
if(typeof customers[t] == ​​"function")//Determine whether it is a function
{
customers[ t]();//Execute
continue;//Return this time and proceed to the next cycle
}
document.write(t ":t" customers[t] "
");
// Output housename: Peninsula Garden Company: vanke A mansion on the top of Dameisha sold for 50 million yuan, a best-selling price! name: Peninsula Garden version: Phase 3 city: Xijia
//Inheritance is realized. Through prototypes.

Summary: I will share this article with you here. Originally, there was a namespace to share. Due to the learning schedule, I will share the Javascript syntax here!

Next time I will share my programming of javascript client and advanced applications such as Jquery.

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

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

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.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

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.

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 Tools

DVWA

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

Safe Exam Browser

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.

mPDF

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.