今天面试,技术问我js闭包、this指向谁。现在想起来,我理解有偏差。技术会不会心里偷笑呢,哈哈哈。吃一堑长一智,做下笔记先。
1 <script type="text/javascript"> 2 /* 3 全局变量、局部变量、变量作用域、链式作用域 4 闭包:可以理解为定义在函数内部的函数,匿名函数是闭包,闭包会导致函数中的变量保存在内存中,有可能会导致性能问题、内存泄漏 5 */ 6 7 function func() { 8 var sum = 0; 9 add = function () { sum += 1 }; //前面没有var,是全局变量、匿名函数 10 function get() 11 { 12 console.log(sum); 13 } 14 return get; 15 } 16 var result = func(); 17 result(); //func().get(); 18 add(); 19 result(); 20 21 22 var name = "The Window"; 23 var object = { 24 name: "My Object", 25 getNameFunc: function () { 26 //return this.name; //My Object,作为对象调用,this指向object 27 return function () { 28 return this.name; //The Window,作为函数调用,this指向window 29 }; 30 } 31 }; 32 console.log(object.getNameFunc()()); 33 </script>
参考: