The most interesting and powerful thing in ECMAScript is the function. Recently, when I was improving my js library, I found that we often use functions, but very few people understand the functions of ECMAScript functions.
1: What is a function?
ECMAScript functions are actually objects. Each function is an instance of the Function type and has properties and methods. Since functions are objects, the function name is actually a pointer to the function object and will not be bound to a certain function. .
2: Method of creating a function
(1):function Person(name)
{
return name;
}
(2):var Person=function(name)
}
(3): var Person=new function("name","return name"); (not recommended, ECMAScript will parse it twice so it is not recommended)
3: The difference between function declarations and function expressions
ECMAScript does not parse function declarations and function expressions equally. The parser will read the function declaration first and make it appear before any code. Available.
Example:
assert(false);
function assert(value, msg) {
if (!value) {
alert (msg || (value " does not equal true"));
}
}
The function expression will not be parsed until this line is executed
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 The properties we often use have roughly similar behavior to Java, C#, and PHP.
For example: window.name='Think about the present with the future' ;
window.name = "Without thinking now;
showName();
function showName() {
alert(this.name);
}
5: Create your own class library plug-in
A brief introduction to functions is not enough for understanding functions, such as constructor mode, prototype mode, prototype Chains and so on take a lot of time to understand.
Create classes
var Class = function () {
var extclass = function () {
//Receive parameters passed by 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 included = obj.included;
for (var i in obj) {
extclass.fn[i] = obj [i];
}
if (included) included(extclass);
}
return extclass;
}
The general framework construction of the class library is completed ,In this way, we can call the extended method when creating a class, and we can call the include method when creating an instance. The next chapter will expand more functions on this basis and add inheritance to "classes" based on prototypes.