Application of metaprogramming
The following examples help you understand the idea of metaprogramming.
(1) generate a new constructor based on the existing object construction, so that the instances of the new object construction have more expressive power than the original object construction instances. For example:
Function createconstructor (FN)
{
VaR P = fn. Prototype;
Function func (){}
// Maintain the prototype chain of the original FN
Func. Prototype = P;
// Maintain the correctness of Object Construction Information
Func. Prototype. constructor = P. constructor;
// Define the new object structure
Func. Prototype. A = "";
Func. Prototype. B = "";
Func. Prototype. MA = function (){};
// Return the new object structure
Return func
}
When a certain type of object has a certain common point, you can use the above code to create an object instance of this type. The essence of this method is prototype chain (prototype chain, refer to the next chapter "javascript operating mechanism ").
(2) extensions of the original function, and these extensions do not affect the syntax structure and functions of the original function. For example:
Function createfunc (FN)
{
// Original FN reference
VaR F = FN;
// Define information for constructing new functions
Function func ()
{
// Function Code of dosomething for FN Extension
Return F. Apply (this, arguments );
}
// Maintain the prototype chain of the original FN
Func. Prototype = fn. Prototype
// Return the new func
Return func
}
As shown in the code above, createfunc returns a new funcion. The input parameter of createfunc is a function. In createfunc, the variable F is used to save the reference to this function, and a new funcion -- func is defined. Func has two roles:
Execute the original function that f points.
You can embed the desired code logic in func, such as printing logs. The addition and deletion of the Code appended to func does not affect the execution logic of the original function.
There are various implementation methods to practice the idea of metaprogramming in JavaScript. Meta-programming can be understood as a programming mode rather than a specific programming method.
This article is recommended by Tu chuanbin and Yang xianting, author of "conquer Ria: javascript-based Web Client development ".