1+ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
2+ < html >
3+ < head >
4+ < title > 命名空间的注入 </ title >
5+ < meta name ="Generator " content ="Vbooking System ">
6+ < meta name ="Author " content ="cwwu ">
7+ < meta name ="Keywords " content ="">
8+ < meta name ="Description " content ="">
9+ < meta http-equiv ="Content-Type " content ="text/html; charset=utf-8 " />
10+ </ head >
11+ < body >
12+ < script type ="text/javascript ">
13+ var myApp = myApp || { } ;
14+ myApp . utils = { } ;
15+
16+ ( function ( ) {
17+ var val = 5 ;
18+
19+ this . getValue = function ( ) {
20+ return val ;
21+ } ;
22+
23+ this . setValue = function ( newVal ) {
24+ val = newVal ;
25+ }
26+
27+ // also introduce a new sub-namespace
28+ this . tools = { } ;
29+
30+ } ) . apply ( myApp . utils ) ;
31+
32+ // inject new behaviour into the tools namespace
33+ // which we defined via the utilities module
34+
35+ ( function ( ) {
36+ this . diagnose = function ( ) {
37+ return "diagnosis" ;
38+ }
39+ } ) . apply ( myApp . utils . tools ) ;
40+
41+ // note, this same approach to extension could be applied
42+ // to a regular IIFE, by just passing in the context as
43+ // an argument and modifying the context rather than just
44+ // "this"
45+
46+ // Usage:
47+
48+ // Outputs our populated namespace
49+ console . log ( myApp ) ;
50+
51+ // Outputs: 5
52+ console . log ( myApp . utils . getValue ( ) ) ;
53+
54+ // Sets the value of `val` and returns it
55+ myApp . utils . setValue ( 25 ) ;
56+ console . log ( myApp . utils . getValue ( ) ) ;
57+
58+ // Testing another level down
59+ console . log ( myApp . utils . tools . diagnose ( ) ) ;
60+ </ script >
61+
62+ </ body >
63+ </ html >
0 commit comments