1+ <!doctype html>
2+ < html lang ="en ">
3+ < head >
4+ < title > JavaScript Patterns</ title >
5+ < meta charset ="utf-8 ">
6+ </ head >
7+ < body >
8+ < script >
9+ /* Title: Klass
10+ Description: generally a pattern that should be avoided unless one is more comfortable with class than prototype
11+ */
12+
13+ var klass = function ( Parent , props ) {
14+
15+ var Child , F , i ;
16+
17+ // 1.
18+ // new constructor
19+ Child = function ( ) {
20+ if ( Child . uber && Child . uber . hasOwnProperty ( "__construct" ) ) {
21+ Child . uber . __construct . apply ( this , arguments ) ;
22+ }
23+ if ( Child . prototype . hasOwnProperty ( "__construct" ) ) {
24+ Child . prototype . __construct . apply ( this , arguments ) ;
25+ }
26+ } ;
27+
28+ // 2.
29+ // inherit
30+ Parent = Parent || Object ;
31+ F = function ( ) { } ;
32+ F . prototype = Parent . prototype ;
33+ Child . prototype = new F ( ) ;
34+ Child . uber = Parent . prototype ;
35+ Child . prototype . constructor = Child ;
36+
37+ // 3.
38+ // add implementation methods
39+ for ( i in props ) {
40+ if ( props . hasOwnProperty ( i ) ) {
41+ Child . prototype [ i ] = props [ i ] ;
42+ }
43+ }
44+
45+ // return the "class"
46+ return Child ;
47+ } ;
48+
49+ var Man = klass ( null , {
50+ __construct : function ( what ) {
51+ console . log ( "Man's constructor" ) ;
52+ this . name = what ;
53+ } ,
54+ getName : function ( ) {
55+ return this . name ;
56+ }
57+ } ) ;
58+
59+ var first = new Man ( 'Adam' ) ; // logs "Man's constructor"
60+ first . getName ( ) ; // "Adam"
61+
62+ var SuperMan = klass ( Man , {
63+ __construct : function ( what ) {
64+ console . log ( "SuperMan's constructor" ) ;
65+ } ,
66+ getName : function ( ) {
67+ var name = SuperMan . uber . getName . call ( this ) ;
68+ return "I am " + name ;
69+ }
70+ } ) ;
71+
72+ var clark = new SuperMan ( 'Clark Kent' ) ;
73+ clark . getName ( ) ; // "I am Clark Kent"
74+
75+ console . log ( clark instanceof Man ) ; // true
76+ console . log ( clark instanceof SuperMan ) ; // true
77+ </ script >
78+ </ body >
79+ </ html >
0 commit comments