关于避免污染命名空间的问题,在Ext中提供了一个专门的namespace函数,可以定义新的命名空间,如下例所示: |
<script type="text/javascript">
//Ext中的命名空间
//比如,我们想给我们自己的项目定义一些工具函数,但又不想污染全局命名空间 Ext.namespace("com.bjsxt.crm.utils");
com.bjsxt.crm.utils.dosomething = function(){ alert("dosomething"); }
com.bjsxt.crm.utils.dosomething();
</script> |
* this变量的概念
<script type="text/javascript">
//理解javascript中的this var a = 100;
alert(a); // 100 alert(this.a); // 100 alert(window.a); // 100
</script> |
<script type="text/javascript">
//理解javascript中的this function GG(){ var a = 1; alert(this.a); }
a = 100;
GG(); // 100 var g = new GG(); //undefined
</script> |
this变量,在执行的时候确定,表示执行的上下文。GG()函数在全局环境中执行,this表示window对象;当通过new操作符来执行构造函数的时候,构造函数内部的this表示的是由new操作符所创建的的对象!
<script type="text/javascript">
//理解javascript中的this function ABC(){ this.something = "something"; }
ABC();
alert(something); // 弹出something
</script> |
ABC()在全局环境中执行,所以执行的时候,this表示window对象,因此后面的alert能够弹出相应的值。
<script type="text/javascript">
//理解javascript中的this function ABC(){ this.something = "something"; }
var abc = new ABC();
alert(something); // 出错!! alert(abc.something); //弹出something,这相当于给abc对象定义了一个公有成员变量
</script> |
new ABC(),导致构造函数内部的this在执行时表示这个abc对象,因此第一句alert出错,因为window全局环境中没有something变量,但是第二句alert将能够得到正确的结果。
<script type="text/javascript"> var x = "I'm a global variable!"; function method() { alert(x); alert(this.x); } function class1() { // private field var x = "I'm a private variable!"; // private method function method1() { //内部函数 alert(x); alert(this.x); } var method2 = method; // public field this.x = "I'm a object variable!"; // public method this.method1 = function() { alert(x); alert(this.x); } this.method2 = method; // constructor { this.method1(); // I'm a private variable! // I'm a object variable! this.method2(); // I'm a global variable! // I'm a object variable! method1(); // I'm a private variable! // I'm a global variable! method2(); // I'm a global variable! // I'm a global variable! method1.call(this); // I'm a private variable! // I'm a object variable! method2.call(this); // I'm a global variable! // I'm a object variable! } }
var o = new class1(); method(); // I'm a global variable! // I'm a global variable! o.method1(); // I'm a private variable! // I'm a object variable! o.method2(); // I'm a global variable! // I'm a object variable! </script> |
记住:内部函数(或称为私有函数)中的this代表window全局对象。但通过call方法,可以改变函数内部的this变量。