JavaScript Advanced Chapter Closure, simulation class, Inheritance (v)

Source: Internet
Author: User
Tags closure

This article mainly shares my understanding of closures and the use of closures to complete the private properties, simulation classes, inheritance, etc., combined with a large number of examples, I hope you can quickly grasp! First, let's start with some basic terminology. One, the closure in JavaScript
1. Let's first understand what is the scope of the function.

2. Called Object

Combined Examples:

Copy CodeThe code is as follows:
function display (something)
{
function ExecuteDisplay1 ()
{
document.write ("I'm helping the boss print:" +something+ "<br/>");//reference to the something parameter of the external function
}
ExecuteDisplay1 ();//function display references an intrinsic function
}
Display ("sorry");//garbage collector after execution is completed
3, closure of the formation

Example I,

Copy CodeThe code is as follows:
var obj = {};//Global object
function Buyhouse (Price,area)
{
return function () {return "The room you want to pay:" +price*area;}; Use an intrinsic function as the return value
}
Obj.people = Buyhouse (12000,80); Save a reference to an intrinsic function in the people property of the Obj object.
This creates a closure, a simple expression: a reference to a nested function is saved to the global scope, whether it is using the value it returns, or the property of the object it exists in.
document.write (Obj.people () + "<br/>");
Example Two,
Copy CodeThe code is as follows:
function Add ()
{
var number = 0;
return function () {return ++number;};/ /
}
var num = Add ();//Is there a 4 reference now, the first global creation: The Access function, the second with an external function (this refers to the anonymous function referred to by the Add ())
The third one is the anonymous function (that is, return functions ...). Refers to the local variable of add), and the fourth is the global object (Var num).
Each call to the global object is persisted in the function body, so the value of the local variable is maintained.
document.write (num ());

The equivalent method
Num2 = (function () {var number = 0;return function () {return ++number;}}) ();//anonymous function, directly assigned to the global object
document.write (num2 ());
Example three, implementing a private property
Copy CodeThe code is as follows:
Using closures to implement private properties
function CreateProperty (O,propertyname,check)
{
var value;
o["Get" +propertyname] = function () {return value;};/ /Returns an anonymous function body to the object's properties
o["Set" +propertyname] = function (v) {if (check &&!check)//Check the legality of the parameter throw ("parameter is wrong!");
else value = V; };//returns an anonymous function body to the object's properties
}
var o = {};
CreateProperty (O, "age", function (x) {return typeof x = = "number";}); /followed by an anonymous function that performs the work of validation, 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 to the properties of the global object.
Second, the class in JavaScript
Also start with some basic terminology!
1. prototype (prototype)

In fact, the prototype of an object is the prototype value of the constructor, all functions are a prototype property, when the function is created is automatically created and initialized, initialize its value is an object, the object comes with a property is constructor, It refers back to the constructor associated with the prototype.
Copy CodeThe code is as follows:
function Peoplehope (money,house)
{
This.money = money;
This.house = House;
}
PeopleHope.prototype.hope = function () {document.write ("I want to have money, house");};/ /This is the prototype, which is initialized to the properties of the object by the constructor.
For (var p in Peoplehope.prototype)
{
document.write ("The prototype came out!") \ t "+ p +" <br/> ");//output: Prototype out! Hope
}
2. Simulation class

In fact, the "class" in JavaScript is just a function. Go directly to the code!
Copy CodeThe code is as follows:
function Peoplehope (money,house)
{
This.money = money;
This.house = House;
Peoplehope.version = Properties of the 0.1//class
peoplehope.createlive = function () {document.write ("under the leadership of the party, our life is very good!") ");} Class method must be a class direct reference
}
3. Inheritance of Classes
Copy CodeThe code is as follows:
function Createclass (name,version)
{
THIS.name = name; Initializing Object Properties
this.version= version;
Createclass.author = "Frank";//Class Property
Createclass.sellhouse = function () {document.write ("We are the real estate leading Enterprise Vanke");};/ Method of the/class
CreateClass.prototype.Company = "Vanke";
CreateClass.prototype.HousePrice = function () {document.write ("Tai Mei Sha Hilltop Mansion sells 50,000,001 sets, selling price! ");};
Prototype, in fact, here you may ask, what is the difference between this prototype and the class method?
In fact, such as var o = new Createclass ("Cofco Real Estate", "Phase One"); The This in the Createclass function is O, and it's connected.
O.name = "Cofco real estate"; o.version = "Phase One";
As for what the prototype is actually doing, you can think of it as a "traitor." When you create an O object, the prototype tells the constructor to take away the initialization.
becomes the property of the object o.
}
function House (name,version,city)
{
Createclass.apply (This,[name,version]);//Inheritance Constructor
this.city = City;
House.prototype.housename = "Peninsula Garden";
}
House.prototype = new Createclass ("Cofco Real Estate", "phase Two");//Get Ceateclass properties, including prototype objects, via new
Prototype properties of the print function
function Displayprototype (c)
{
for (var x in C.prototype)
{
document.write (x+ "<br/>");
}
}
Displayprototype (House);//output: Houseprice company Name version
Delete objects that are not prototypes
Delete house.prototype.name;//Remove
Delete house.prototype.version;//Remove
Displayprototype (House);//output: Houseprice Company
var customers = new House ("Peninsula Garden", "Phase Three", "West Tooth Extraction");
for (Var t in customers)
{
if (typeof customers[t] = = "function")//judgment is not
{
Customers[t] ();//execution
continue;//return this time for the next cycle
}
document.write (t + ": \ T" + customers[t]+ "<br/>");
Output housename: The Peninsula Garden Company:vanke Tai Mei Sha Hilltop Mansion sells 50,000,001 sets, sells the price! Name: Peninsula Garden Version: Three issue city: West Tooth
The inheritance is realized. Through prototypes.
Summary: This article and everyone to share here, there are also namespaces to share, due to the relationship between learning time, JavaScript syntax for everyone to share here!

Next time I'm going to share my programming with JavaScript and advanced applications like jquery.

JavaScript Advanced Chapter Closure, simulation class, Inheritance (v)

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.