🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~javascript 1.var num = 10; 2.var obj = {num: 20}; 3.obj.fn = (function (num) { 4. this.num = num * 3; 5. num++; 6. return function (n) { 7. this.num += n; 8. num++; 9. console.log(num); 10. } 11.})(obj.num); 12.var fn = obj.fn; 13.fn(5); //22 14.obj.fn(10); //23 15.console.log(num, obj.num); //65 30 ~~~ ![](https://img.kancloud.cn/fa/81/fa8141b05a6a2016fc7c9a664b6cafaa_526x275.png) ~~~ /* * 变量提升: * var num; * var obj; * var fn; */ var num = 10, obj = {num: 20};//=>obj=aaafff000 =>{num:20,fn:bbbfff000} obj.fn = (function (num) { /* * num=10 * this->window */ num = this.num + 10;//=>num=20 (21) (22) this.num = num + 10;//=>window.num=30 return function () {//=>bbbfff000 /* * fn() * this->window * window.num+= ++num; //=>window.num=51 */ /* * obj.fn() * this->obj * obj.num+= ++num; //=>obj.num=42 */ this.num += ++num; } })(num); var fn = obj.fn;//=>fn=bbbfff000 fn(); obj.fn(); console.log(num, obj.num); ~~~ ![](https://img.kancloud.cn/d0/b4/d0b4758aee15b0f342becf9304a99a2f_2724x1044.png)