The most interesting and powerful part of ECMAScript is the function. When we improved our js class libraries, we found that we often use functions, but few really know the functions of ECMAScript.
1: What is a function?
The ECMAScript Function is actually an object. Every Function is a Function-type instance and has attributes and methods. Because the Function is an object, the Function name is actually a pointer to the Function object and will not be bound to a Function.
2: Create a function
Copy codeThe Code is as follows: (1): function Person (name)
{
Return name;
}
(2): var Person = function (name)
{
Return name;
}
(3): var Person = new function ("name", "return name"); (not recommended. ECMAScript will parse twice, so it is not recommended)
3: function declaration and function expression are different
ECMAScript does not treat function declaration and function expression parsing equally. The parser first reads the function declaration and makes it available before any code.
Example:Copy codeThe Code is as follows: assert (false );
Function assert (value, msg ){
If (! Value ){
Alert (msg | (value + "does not equal true "));
}
}
Function expressions are parsed only when this line is executed.Copy codeThe Code is as follows: for example, assert (false );
Var assert = function (value, msg ){
If (! Value ){
Alert (msg | (value + "does not equal true "));
}
}
4: Understand this attribute
This attribute is a commonly used attribute. Its behavior is similar to that of Java, C #, and PHP.Copy codeThe Code is as follows: for example, window. name = 'think about the present in the future ';
Window. name = "not thinking about the present;
ShowName ();
Function showName (){
Alert (this. name );
}
5. Create your own class library plug-in
A simple introduction to functions is far from enough to understand functions, such as constructor mode, prototype mode, and prototype chain.
Create classCopy codeThe Code is as follows: var Class = function (){
Var extclass = function (){
// Receives parameters from attributes
This. init. apply (this, arguments );
}
// Add custom attributes to the class
Extclass. prototype. init = function (){};
// Define an alias for prototypr?
Extclass. fn = extclass. prototype;
// Define the alias of the class?
Extclass. fn. parent = extclass;
// Add attributes to the class
Extclass. extend = function (obj ){
Var extended = obj. extended;
For (var I in obj ){
Extclass. fn [I] = obj [I];
}
If (extended) extended (extclass );
};
// Add attributes to the instance
Extclass. include = function (obj ){
Var encoded DED = obj. Encoded DED;
For (var I in obj ){
Extclass. fn [I] = obj [I];
}
If (sorted DED) Sorted ded (extclass );
}
Return extclass;
}
The general framework of the class library is built, so that we can call the extended method to create a class and call the include method to create an instance. The next section will expand more functions and add inheritance to the class based on the prototype.