Closure and simulation class in JavaScript advanced, inheritance (6)

Source: Internet
Author: User
In this advanced article, I will share my understanding of closures and the use of closures to complete private attributes, simulation classes, inheritance, and so on. I hope you can master them quickly with a large number of examples! First, let's start with some basic terms! I. Closure in javascript 1. Let's first understand what functions are... SyntaxHighlighter. all ();

Advanced
This article mainly shares my understanding of closures and the use of closures to complete private attributes, simulation classes, inheritance, and so on. In combination with a large number of examples, I hope you can quickly master them! First, let's start with some basic terms!

I. Closure in javascript
1. Let's first understand what is the function scope.


2. called object

 

 

Examples:
Function display (something)
{
Function executeDisplay1 ()
{
Document. write ("I am printing for my boss:" + something +"
"); // Reference the something parameter of the external Function
}
ExecuteDisplay1 (); // The function display references the internal function
}
Display ("sorry"); // It is recycled by the garbage collector after execution.
3. Closure Formation

 


 

Example 1,
Var obj = {}; // Global Object
Function buyHouse (price, area)
{
Return function () {return "the payment you want to pay:" + price * area;}; // use the internal function as the return value.
}
Obj. people = buyHouse (, 80); // Save the reference of the internal function to the people attribute of the obj object.
// This forms a closure, simple expression: Save the reference of the nested function to the global scope, whether it is to use the value returned by it or to store it in the attributes of the object.
Document. write (obj. people () +"
");
Example 2,
Function add ()
{
Var number = 0;
Return function () {return ++ number ;};//
}
Var num = add (); // is there 4 references now? First Global creation: access function, second external function (here it refers to Add () reference anonymous functions)
// The third is the anonymous function (return function... references the local variable of Add), and the fourth is the Global Object (var num.
// The objects called by global objects are still stored in the function body, so the values of local variables are 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: Implement private attributes
// Use closures to implement private attributes
Function createProperty (o, propertyname, check)
{
Var value;
O ["get" + propertyname] = function () {return value ;}; // returns the attribute of an anonymous function to the object.
O ["set" + propertyname] = function (v) {if (check &&! Check) // check the validity of the parameter throw ("the parameter is incorrect! ");
Else value = v ;}; // returns the attributes of an anonymous function to the object.
}
Var o = {};
CreateProperty (o, "Age", function (x) {return typeof x = "number" ;}); // an anonymous function is followed to perform verification, returns false if it is not a number.
O. setAge (22); // use Object Attributes
Document. write (o. getAge ());

// Actually, the function is saved to the attributes of the global object.
Ii. Class www.2cto.com in javascript
Also, let's 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 a function is created, it is automatically created and initialized, the initialization value is an object. This object comes with a constructor attribute, which refers 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, house") ;}; // This is the prototype, and will be initialized by the constructor to the attributes of the object.
For (var p in PeopleHope. prototype)
{
Document. write ("the prototype has come out! \ T "+ p +"
"); // Output: The prototype is displayed! Hope
}
2. Simulation
In fact, the "class" in Javascript is just a function. Go directly to the code!
Function PeopleHope (money, house)
{
This. money = money;
This. house = house;
Lelehope. VERSION = 0.1 // attributes of the class
PeopleHope. createLive = function () {document. write ("under the leadership of the Party, we have a good life! ");} // The class method must be directly referenced by the class
}
3. class inheritance
Function CreateClass (name, version)
{
This. name = name; // initialize object attributes
This. version = version;
CreateClass. AUTHOR = "Frank"; // class attributes
CreateClass. SellHouse = function () {document. write ("Vanke, a leading real estate company") ;}; // method of the class
CreateClass. prototype. Company = "vanke ";
CreateClass. prototype. HousePrice = function () {document. write! ");};
// Prototype. You may ask here, what is the difference between this prototype and the class method?
// It is actually: for example, var o = new CreateClass ("Zhongliang Real Estate", "Phase I"); this in the CreateClass function is o, and the connection is
// O. name = "Zhongliang Real Estate"; o. version = "Phase I!
// As to what the prototype is actually doing, you can understand it as a "traitor". When you create the o object, the prototype tells the constructor to take the initialization together.
// Becomes the attribute of object o.
}
Function House (name, version, city)
{
CreateClass. apply (this, [name, version]); // inherit the constructor
This. city = city;
House. prototype. housename = "Peninsula Garden ";
}
House. prototype = new CreateClass ("Zhongliang property", "Phase II"); // obtain 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 an object that is not a prototype
Delete House. prototype. name; // delete
Delete House. prototype. version; // delete
DisplayPrototype (House); // output: HousePrice Company
Var customers = new House ("Peninsula Garden", "phase III", "West tooth extraction ");
For (var t in mers)
{
If (typeof MERs [t] = "function") // determines if it is a function.
{
Customers [t] (); // Execute
Continue; // returns this time for the next loop
}
Document. write (t + ": \ t" + MERs [t] +"
");
// Output housename: Peninsula Garden Company: vanke Dameisha mountain mansion sold for million sets, the best selling price! Name: Peninsula Garden version: Phase III city: West Tooth Extraction
// Inheritance is implemented. By prototype.
Summary: I will share this article with you. There is still a namespace to share with you. Due to the learning schedule, I will share the Javascript syntax here!
Next time, I will share my javascript client programming and Jquery and other advanced applications.

 

From ben2012


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.