<script type="text/javascript">
//理解javascript中的this var obj1 = { prop1:"obj1:世界,你好", hello:function(){ alert("obj1 alert:"+this.prop1); } };
var obj2 = { prop1:"obj2:世界,你好", hello:function(){ alert("obj2 alert:"+this.prop1); } };
obj1.hello(); obj2.hello();
//通过call方法,可以改变函数内部的this的值 obj1.hello.call(obj2);
</script> |
上述例子,演示了如何通过call操作改变this变量的。
<script type="text/javascript">
//理解javascript中的this function GG(){ this.something = 200; alert(this.something); function G1(){ alert(this.something); function G2(){ alert(this.something); } G2(); } G1(); }
something = 100;
var g = new GG(); // 100
</script> |
再一次演示:内部函数中的this表示全局的window对象
<script type="text/javascript">
//理解javascript中的this function GG(){ this.something = 200; function G1(){ function G2(){ alert(this.something); } G2.call(this); } G1.call(this); }
something = 100;
var g = new GG();
</script> |
再一次演示:如何改变内部函数中的this变量
<script type="text/javascript">
//理解javascript中的this //x,y是函数的形参 function fn(x,y){ alert(this);
//arguments是函数的实参 alert("传进来的参数长度是? - " + arguments.length); alert(x + y); }
fn(34,50,80); //object,3,84
fn.call(23,50,51,52); //23,3,101
</script> |
演示:如何改变函数中的this变量
Javascript中的闭包
<script type="text/javascript"> |
返回内部函数,内部函数引用外部函数的变量,使得外部函数的变量会在内存中一直存在(也使得这个变量只能被内部函数使用,即封装),这就叫“闭包”。