The tool functions are as follows:
View sourceprint? 01 /**
02 * $ class write tool function 3
03 * @ param {String} className
04 * @ param {Function} superClass
05 * @ param {Function} classImp
06 */
07 function $ class (className, superClass, classImp ){
08 if (superClass = "") superClass = Object;
09 var clazz = function (){
10 return function (){
11 if (typeof this. init = "function "){
12 this. init. apply (this, arguments );
13}
14 };
15 }();
16 var p = clazz. prototype = new superClass ();
17 var _ super = superClass. prototype;
18 window [className] = clazz;
19 classImp. apply (p, [_ super]);
20}
Define a Person class
View sourceprint? 01 $ class (Person, function (){
02 // Constructor
03 this. init = function (name ){
04 this. name = name;
05 };
06 // method body
07 this. getName = function (){
08 return this. name;
09 };
10 this. setName = function (name ){
11 this. name = name;
12 };
13 });
Create an object
View sourceprint? 1 var p = new Person (Jack );
2 console. log (p );
3 console. log (p. constructor = Person); // false
Use this tool to write classes. this. init method is essential. Students who have used Prototype Libraries know that the initialize method after Class. create is also essential.
Because inheritance is not considered, the second parameter superClass uses an empty string, that is, it inherits from the Object by default.
If the output is false, this tool class does not maintain the constructor attribute. There is a trade-off between each write type of the design, which depends entirely on the intent of the designer.