Create class:
VaR Class = Function (Parent ){ VaR Klass = Function (){ This . Init. Apply ( This , Arguments );}; If (Parent ){ VaR Subclass = Function () {}; Subclass. Prototype = Parent. Prototype; Klass. Prototype = New Subclass;} Klass. Prototype. init = Function () {}; Klass. FN = Klass. Prototype; Klass. FN. Parent = Klass; Klass. Proxy = Function (Func ){ VaR Self = This ; Return ( Function () {Func. Apply (self, arguments) ;}) ;}; Klass. FN. Proxy = Klass. Proxy; Klass. Extend = Function (OBJ ){ VaR Extended = OBJ. extended; For ( VaR I In OBJ) {Klass [I] = OBJ [I];} If (Extended) extended (Klass)}; Klass. Include = Function (OBJ ){ VaR Required DED = OBJ. included; For ( VaR I In OBJ) {Klass. FN [I] = OBJ [I];} If (Sorted DED) Sorted ded (Klass )}; Return Klass ;};
Demo:
VaR Person = New Class; person. Include ({init: Function (Name, age ){ This . Name = Name; This . Age = person. checkage (AGE )? Age: Null ;}, Sayhello: Function () {Console. Log ( "Hi, my name is" + This . Name + ( This . Age? ", I am" + This . Age + "years old this year ":"" ) ;}}); Person. Extend ({needwater: True , Checkage: Function (AGE ){ Return Age> 0 & age <150 ;}}); VaR Jim = New Person ("Jim", 10); Jim. sayhello (); // Output: Hi, my name is Jim, I am 10 years old this year VaR Tom = New Person ("Tom",-1 ); Tom. sayhello (); // Output: Hi, my name is Tom
There are static attributes and methods in extend, and instance attributes and methods in include.
When attributes and methods are irrelevant to or public to specific instances, use static attributes and Methods. Otherwise, use instance attributes and methods.