I. function
From the very beginning, when I got started with JavaScript, I felt flexible. Everyone's writing methods were different. For example, a function had N writing methods.
For example: function showMsg () {}, var showMsg = function () {}, showMsg = function (){}
There seems to be no difference. They are all the same. Is it true? Let's take a look at the example below.
Copy codeThe Code is as follows:
/// Response ///-----------------------------------------------------------------------------------------
-------
// Function Definition: Name function (declarative), anonymous function (reference)
// Declarative, defining code to be parsed before function Execution Code
Function t1 (){
Dwn ("t1 ");
}
T1 ();
Function t1 (){
Dwn ("new t1 ");
}
T1 ();
// Reference type for dynamic parsing during function running
Var t1 = function (){
Dwn ("new t1 ");
}
T1 ();
Var t1 = function (){
Dwn ("new t1 ");
}
T1 ();
// Output above: new t1, new t1, new t1, new t1
The output may be t1, new t1, new newt1, new t1, but the result is not like this. We should understand this sentence: declare
Before the function Execution Code is parsed.
If we take a further step, we should say that it is a scope chain problem. In fact, the first two methods are equivalent to window. t1, which can be understood as window.
A public attribute is assigned two times, with the last value assigned as the final value
The next two methods can be understood as t1 is a variable, and the result after var of the fourth method is removed remains unchanged.
However, when the fourth method is changed to a declaration like function t1 () {}, the result is changed to new t1, new
T1, new t1, new t1
According to my understanding, the first two can better understand why this is the answer, and the third can also understand it, but the last output makes me compare
It's quite tangled. I hope some experts can answer this question.
In addition, anonymous functions are written like (function () {...}) (). The last bracket is used for parameter input.
There is also a declaration such as var t1 = new function () {...}. In fact, t1 is already an object.
Example:
Copy codeThe Code is as follows:
Var t2 = new function ()
{
Var temp = 100; // Private member
This. temp = 200; // public member. The two concepts will be described later in the third part.
Return temp + this. temp;
}
Alert (typeof (t2); // object
Alert (t2.constructor (); // 300
In addition, a built-in function object is used to construct a function, for example:
Var t3 = new Function ('var temp = 100; this. temp = 200; return temp + this. temp; '); // The result is the same if this position is added without adding new, WHY
Alert (typeof (t3); // function
Alert (t3 (); // 300
2. Create an object
First, let's take a look at Object-Oriented Programming (Object-Oriented Programming, OOP). Using OOP technology, we often use a lot
Code module. Each module provides specific functions. Each module is isolated and even completely independent from other modules.
. This modular programming method provides great diversity and greatly increases the chance of code reuse. You can give an example to further illustrate this question.
Suppose a high-performance application on the computer is a first-class racing car. If you use traditional programming skills, this car is
A unit. To improve the car, you must replace the entire unit, send it back to the manufacturer, ask the car experts to upgrade it, or buy a new
Car. If you use OOP technology, you only need to purchase a new engine from the manufacturer and replace it with the instructions, instead of using a steel saw to cut the car body.
However, most of the arguments are that javascript is not a direct object-oriented language, but many object-oriented languages can be implemented through simulation.
What can be done by words, such as inheritance, polymorphism, encapsulation, and javascript (nothing can be done, but unexpected)
Copy codeThe Code is as follows:
/// Response ///-----------------------------------------------------------------------------------------
-------
// The following three methods for constructing objects:
// New Object: instantiate an Object
Var a = new Object ();
A. x = 1, a. y = 2;
// Object Direct Volume
Var B = {x: 1, y: 2 };
// Define the type
Function Point (x, y) {// similar to the class in C #
This. x = x;
This. y = y;
}
Var p = new Point (1, 2); // instantiate the class
The first method is implemented by constructing a basic object to directly add attributes. The second method is similar to the first method.
Quick Representation
In the third method, you can create multiple objects of the same type based on the "class ".
3. encapsulation of object attributes (public and private)
Example
Function List (){
Var m_elements = []; // Private member, which cannot be accessed outside the object. If there is no var declaration, m_elements is changed to global
In this way, external access can be directly obtained, such as alert (m_elements [0]).
Copy codeThe Code is as follows:
M_elements = Array. apply (m_elements, arguments );
// Simulate getter here. alist. length is used;
// Equivalent to the getName () method: this. length = function () {return m_elements.length ;}.
Alist. length ();
// Public attribute, which can be accessed through the "." operator or subscript
This. length = {
ValueOf: function (){
Return m_elements.length;
},
ToString: function (){
Return m_elements.length;
}
}
// Public method. This method uses alert (alist) equivalent to alert (alist. toString ())
This. toString = function (){
Return m_elements.toString ();
}
// Public Method
This. add = function (){
M_elements.push.apply (m_elements, arguments );
}
// The Private method is as follows. The closure concept is involved here.
// Var add = function () or function add ()
//{
// M_elements.push.apply (m_elements, arguments );
//}
}
Var alist = new List (1, 2, 3 );
Dwn (alist); // = alert (alist. toString (), output 1, 2, 3
Dwn (alist. length); // output 3
Alist. add (4,5, 6 );
Dwn (alist); // output 1, 2, 3, 4, 5, 6
Dwn (alist. length); // output 6
Iv. Types of attributes and Methods
In javascript, object attributes and Methods support four different types: private property and dynamic public.
Property (dynamic public property), static public property/prototype property (static public property or prototype property ),
Static property (static property or class property ). Private attributes are completely inaccessible to the outside world. You can use the internal getter and
Setter (both simulated); the dynamic public attribute can be accessed from outside, and each object instance holds a copy without affecting each other; prototype
Each object instance shares a unique copy of an attribute. A class attribute is not an attribute of an instance but a property of a class.
The following is an example:
Copy codeThe Code is as follows:
/// Response ///-----------------------------------------------------------------------------------------
-------
// Dynamic public type, static public type (prototype attribute)
Function myClass (){
Var p = 100; // private property
This. x = 10; // dynamic public property
}
MyClass. prototype. y = 20; // static public property or prototype property, dynamically added to the prototype of myClass
Adding properties will act on all instantiated objects. Note that prototype is used here, which is very useful.
// To become an advanced javascript stage, prototype and closure must be understood and properly applied
MyClass. z = 30; // static property
Var a = new myClass ();
Dwn (a. p) // undefined
Dwn (a. x) // 10
Dwn (a. y) // 20
A. x = 20;
A. y = 40;
Dwn (a. x); // 20
Dwn (a. y); // 40
Delete (a. x); // delete the attribute x of object
Delete (a. y); // delete the property y of object
Dwn (a. x); // undefined
Dwn (a. y); // 20 the static public property y is deleted and restored to the prototype property y.
Dwn (a. z); // undefined class attributes cannot be accessed through objects
Dwn (myClass. z );
V. prototype)
I will only talk about this part. prototype and closure can be clearly explained in a few words. If we can give you some inspiration here, I'm lucky.
Idioms "show Cats and tigers". The cat here is the prototype, and the tiger is the type, which can be expressed as: Tiger. prototype = a cat or
Tiger. prototype = new CAT ()
Because each object instance of the prototype attribute shares a unique copy, when one of the instances adjusts the value of a prototype attribute
This attribute will change.
The following is the type chain of the prototype relationship:
Copy codeThe Code is as follows:
Function ClassA (){
}
ClassA. prototype = new Object ();
Function ClassB (){
}
ClassB. prototype = new ClassA ();
Function ClassC (){
}
ClassC. prototype = new ClassB ();
Var obj = new ClassC ();
Dwn (obj instanceof ClassC); // true
Dwn (obj instanceof ClassB); // true
Dwn (obj instanceof ClassA); // true
Dwn (obj instanceof Object); // true
Point Object with default values:
Function Point2 (x, y ){
If (x) this. x = x;
If (y) this. y = y;
}
// Set x of the Point2 object. The default value of y is 0.
Point2.prototype. x = 0;
Point2.prototype. y = 0;
// P1 is a default (0, 0) object
Var p1 = new Point2 (); // It can be written as var p1 = new Point2 without error, WHY
// P2 assignment
Var p2 = new Point2 (1, 2 );
Dwn (p1.x + "," + p1.y); // 0, 0
Dwn (p2.x + "," + p2.y); // 1, 2
After the delete object property is deleted, the prototype property will return to the initialization status:
Function ClassD (){
This. a = 100;
This. B = 200;
This. c = 300
}
ClassD. prototype = new ClassD (); // set the original attribute of ClassD as a prototype, including its value
ClassD. prototype. reset = function () {// delete a non-prototype attribute
For (var each in this ){
Delete this [each];
}
}
Var d = new ClassD ();
Dwn (d. a); // 100
D. a * = 2;
D. B * = 2;
D. c * = 2;
Dwn (d. a); // 200
Dwn (d. B); // 400
Dwn (d. c); // 600
D. reset (); // Delete non-prototype attributes. All returned prototype
Dwn (d. a); // 100
Dwn (d. B); // 200
Dwn (d. c); // 300
Vi. Inheritance
If both classes are of the same instance type, there is a certain relationship between them. We generalize the types of the same instance.
A link is called inheritance. C # and JAVA both have this. The specific understanding will not be mentioned.
In javascript, The method does not support inheritance directly, but as mentioned above, it can be simulated.
There are four methods: Construction inheritance, prototype inheritance, instance inheritance, and copy inheritance. After the integration, there will be a mixture
What method is this, that is, the first four methods are mixed ~
The following example is from Return of the King, which involves the use of apply, call, and some arrays. If you are interested, you can search in the garden.
Click
1. Example of construction continuation method:
Copy codeThe Code is as follows:
// Define a Collection type
Function Collection (size)
{
This. size = function () {return size}; // public method, which can be inherited
}
Collection. prototype. isEmpty = function () {// static method, which cannot be inherited
Return this. size () = 0;
}
// Define an ArrayList type, which "inherits" Collection type
Function ArrayList ()
{
Var m_elements = []; // Private member, which cannot be inherited
M_elements = Array. apply (m_elements, arguments );
// ArrayList inheritance Collection
This. base = Collection;
This. base. call (this, m_elements.length );
This. add = function ()
{
Return m_elements.push.apply (m_elements, arguments );
}
This. toArray = function ()
{
Return m_elements;
}
}
ArrayList. prototype. toString = function ()
{
Return this. toArray (). toString ();
}
// Define a SortedList type, which inherits the ArrayList type
Function SortedList ()
{
// The SortedList type inherits the ArrayList
This. base = ArrayList;
This. base. apply (this, arguments );
This. sort = function ()
{
Var arr = this. toArray ();
Arr. sort. apply (arr, arguments );
}
}
// Construct an ArrayList
Var a = new ArrayList (1, 2, 3 );
Dwn ();
Dwn (a. size (); // a inherits the size () method from the Collection.
Dwn (a. isEmpty); // but a does not inherit the isEmpty () method
// Construct a SortedList
Var B = new SortedList (3,1, 2 );
B. add (); // B inherits the add () method from ArrayList
Dwn (B. toArray (); // B inherits the toArray () method from ArrayList
B. sort (); // The sort () method implemented by B.
Dwn (B. toArray ());
Dwn (B );
Dwn (B. size (); // B inherits the size () method from the Collection.
2. Example of prototype Inheritance Law:
Copy codeThe Code is as follows:
// Define a Point type
Function Point (dimension)
{
This. dimension = dimension;
}
// Define a Point2D type and "inherit" Point type
Function Point2D (x, y)
{
This. x = x;
This. y = y;
}
Point2D. prototype. distance = function ()
{
Return Math. sqrt (this. x * this. x + this. y * this. y );
}
Point2D. prototype = new Point (2); // Point2D inherits the Point
// Define a Point3D type and inherit the Point type
Function Point3D (x, y, z)
{
This. x = x;
This. y = y;
This. z = z;
}
Point3D. prototype = new Point (3); // Point3D also inherits the Point
// Construct a Point2D object
Var p1 = new Point2D (0, 0 );
// Construct a Point3D object
Var p2 = new Point3D (0, 1, 2 );
Dwn (p1.dimension );
Dwn (p2.dimension );
Dwn (p1 instanceof Point2D); // p1 is a Point2D
Dwn (p1 instanceof Point); // p1 is also a Point
Dwn (p2 instanceof Point); // p2 is a Point
The above two methods are the most commonly used
3. Example of the instance inheritance law:
Before giving an example of this method, let's talk about the limitations of constructing the inheritance method as follows:
Copy codeThe Code is as follows:
Function MyDate ()
{
This. base = Date;
This. base. apply (this, arguments );
}
Var date = new MyDate ();
Alert (date. toGMTString); // undefined, date does not inherit the Date type, so there is no toGMTString Method
Some methods of the core object cannot be inherited by the constructor because the core object does not enter
Row assignment or Initialization
What about the prototype inheritance law ?, As follows:
Copy codeThe Code is as follows:
Function MyDate (){}
MyDate. prototype = new Date ();
Var date = new MyDate ();
Alert (date. toGMTString); // '[object]' is not a Date object and is still not inherited to the date type!
Now, change to the instance inheritance law:
Copy codeThe Code is as follows:
Function MyDate ()
{
Var instance = new Date (); // instance is a newly created Date object.
Instance. printDate = function (){
Document. write ("<p>" + instance. toLocaleString () + "</p> ");
} // Extend the printDate () method to the instance
Return instance; // use the instance as the return value of the constructor.
}
Var myDate = new MyDate ();
Dwn (myDate. toGMTString (); // the correct time string is successfully output this time. It seems that myDate is already an instance of Date.
Succeeded
MyDate. printDate (); // if no return instance exists, the following mark cannot be accessed because it is a private object method.
4. Copy the inheritance law example:
Copy codeThe Code is as follows:
Function. prototype. extends = function (obj)
{
For (var each in obj)
{
This. prototype [each] = obj [each];
// One-to-one copying of object attributes, but it is slow and prone to Problems
// Therefore, this "inheritance" method is generally not recommended
}
}
Var Point2D = function (){
//......
}
Point2D. extends (new Point ())
{
//......
}
This inheritance law seems to be rarely used.
5. Example of hybrid inheritance:
Copy codeThe Code is as follows:
Function Point2D (x, y)
{
This. x = x;
This. y = y;
}
Function ColorPoint2D (x, y, c)
{
Point2D. call (this, x, y); // here constructor inheritance is called, and the constructor of the parent class is called.
// From the previous example, it is equivalent
// This. base = Point2D;
// This. base. call (this, x, y );
This. color = c;
}
ColorPoint2D. prototype = new Point2D (); // prototype inheritance is used here to make ColorPoint2D prototype Point2D