//对象中的闭包this会指向window,2种方式改变作用域
var color="系统"; var obj={ color:"局部", run:function(){ /*var that=this;*/ return function(){ return this.color; } } } document.write(obj.run().call(obj));
//封装for循环,把k锁定在函数内部 var box = function(i) { (function() { for (var k = 0; k < i; k++) { document.write(k); }; })(i);//在此外面,i即不可用,防止变量污染 }; box(9);
//把对象的里的属性,方法变为私有,通过接口访问 function Box () { this.age=100; } function Box1(){ var age=100; function run(){ return 1234; } this.publicGo=function(){ return age+run(); } } var box=new Box1(); alert(box.publicGo());