Preface:
It seems that there are fewer people in the garden recently.ArticleThe reading volume is much less.
The purpose of writing this article is to make moreProgramUnderstanding JavaScript concepts, not understanding
We already know enough about it. It's time to move closer to the deeper understanding.
Why do you say that, if you receive an interview invitation a few days ago, you can try it. You haven't had an interview for a few years.
Sitting on the sofa with the interviewer, he asked me in a simple way: The following are some JavaScript problems.
> Create an object with several public attributes. Next, create a public method for the object, create several private attributes for the object, and create a private method.
To be honest, I have a silent name for these questions. If he asks me to use jquery to write a drag plug-in or something, I guess I can write very well. The native Javascript is dizzy. Although I have read the jquery source code explanation, but these basic concepts are terrible.
Later, I will write the answer in the body
If the interviewer is reading, say thank you. After the interview, I will go to the Shenzhen Book Purchasing Center to buy JavaScript, which is very expensive.
Then I did not do anything. I carefully watched it for more than a week. If I couldn't understand it, I came to the garden to find it. There were so many treasures in the garden! (A rhyme is also pressed ...)
The example output in this article is as follows for ease of viewing
Function dwn (s ){
Document. Write (S + "<br/> ");
}
Some of the following content is original, some are from the Internet, or can be considered as reading notes. If there is anything wrong with it, please kindly advise and be grateful.
Start of Text :
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.
/// Response ///------------------------------------------------------------------------------------------------
// Function Definition: Name function (declarative), anonymous function (reference)
// Declarative, defined Code 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
I may think that I should output T1, new T1, new newt1, New T1, but the result is not like this. I should understand this sentence: declarative, the defined code is parsed before the function Execution Code.
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. It can be understood that T1 is a public attribute of window. It is assigned twice and the last value is 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. However, the last output makes me more difficult. 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:
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). With OOP technology, many code modules are often used, and 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. This problem can be further illustrated by examples, assuming that 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 through simulation, it can do a lot of things that can be done by object-oriented languages, such as inheritance, polymorphism, encapsulation, javascript can be used)
/// 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 add attributes directly. The second method is similar to the first one, which can be seen as a quick representation of the first method.
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 here, m_elements will be changed to a global variable so that the external member can be accessed directly, for example, alert (m_elements [0])
M_elements = array. Apply (m_elements, arguments );
// Simulate getter here. alist. length is used;
// Equivalent to getname (): 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
4. Type of attributes and methods
in Javascript, four different types of attributes and methods are supported: private property (private property), 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. They can be accessed through internal getter and setter (both simulated). dynamic public attributes can be accessed from outside, and each object instance holds a copy without affecting each other; prototype
attributes: each object instance shares a unique copy. A class attribute is not an instance attribute but a class attribute.
The following is an example:
// dynamic public type, static public type (prototype attribute)
function myclass () {
var P = 100; // Private Property
This. X = 10; // dynamic public property
}< br> myclass. prototype. y = 20; // static public property or prototype property. attributes are dynamically added to the prototype of myclass, which applies to all instantiated objects. Note that prototype is used here, this is a very useful stuff
// prototype and closure must be understood and properly applied to become an advanced JavaScript stage
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 a prototype, and the tiger is a 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, all instances change when calling this attribute.
The following is the type chain of the prototype relationship:
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
6. Inheritance
if both classes are of the same instance type, there is a relationship between them, we call the generalized relationship between the types of the same instance as inheritance. C # and Java both have this. The specific understanding will not be mentioned.
in Javascript, methods do not support inheritance directly, but as mentioned earlier, it can be simulated.
there are four methods: Constructing inheritance methods, prototype inheritance, instance inheritance, and copy inheritance. After the integration, there will be a hybrid continuation method. What is this method, that is, the first four types of mixing ~
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 for them in the garden.
1, example of construction Continuation Method:
// defines a collection type
function collection (size)
{< br> This. size = function () {return size}; // public method, which can be inherited
}< br>
collection. prototype. isempty = function () {// static method, cannot be inherited
return this. size () = 0;
}< br>
// defines an arraylist type, which "inherits" collection type
function arraylist ()
{< br> 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:
// 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:
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 is not assigned values or initialized in the constructor as the general object we customize.
What about the prototype inheritance law ?, 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:
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 and is successfully inherited.
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:
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:
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
I still want to continue writing the closure, but it is really difficult to write this. I also spent several hours trying to figure it out. I recommend the following blog:
Http://www.cnblogs.com/rubylouvre/archive/2009/07/24/1530074.html#1884486
I hope the above articles will inspire readers. If there are any errors, please leave a message. If you think it is not bad,You can click in the lower right corner to recommend to more people.