


JavaScript 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:
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,
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,
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
//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.
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!
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
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.

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

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

In function inheritance, use "base class pointer" and "derived class pointer" to understand the inheritance mechanism: when the base class pointer points to the derived class object, upward transformation is performed and only the base class members are accessed. When a derived class pointer points to a base class object, a downward cast is performed (unsafe) and must be used with caution.

In C++, a closure is a lambda expression that can access external variables. To create a closure, capture the outer variable in the lambda expression. Closures provide advantages such as reusability, information hiding, and delayed evaluation. They are useful in real-world situations such as event handlers, where the closure can still access the outer variables even if they are destroyed.

A closure is a nested function that can access variables in the scope of the outer function. Its advantages include data encapsulation, state retention, and flexibility. Disadvantages include memory consumption, performance impact, and debugging complexity. Additionally, closures can create anonymous functions and pass them to other functions as callbacks or arguments.

C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.

Inheritance error debugging tips: Ensure correct inheritance relationships. Use the debugger to step through the code and examine variable values. Make sure to use the virtual modifier correctly. Examine the inheritance diamond problem caused by hidden inheritance. Check for unimplemented pure virtual functions in abstract classes.

Detailed explanation of C++ function inheritance: Master the relationship between "is-a" and "has-a" What is function inheritance? Function inheritance is a technique in C++ that associates methods defined in a derived class with methods defined in a base class. It allows derived classes to access and override methods of the base class, thereby extending the functionality of the base class. "is-a" and "has-a" relationships In function inheritance, the "is-a" relationship means that the derived class is a subtype of the base class, that is, the derived class "inherits" the characteristics and behavior of the base class. The "has-a" relationship means that the derived class contains a reference or pointer to the base class object, that is, the derived class "owns" the base class object. SyntaxThe following is the syntax for how to implement function inheritance: classDerivedClass:pu

Go language function closures play a vital role in unit testing: Capturing values: Closures can access variables in the outer scope, allowing test parameters to be captured and reused in nested functions. Simplify test code: By capturing values, closures simplify test code by eliminating the need to repeatedly set parameters for each loop. Improve readability: Use closures to organize test logic, making test code clearer and easier to read.

Yes, code simplicity and readability can be optimized through chained calls and closures: chained calls link function calls into a fluent interface. Closures create reusable blocks of code and access variables outside functions.
