this是学习每门语言的必备,this理解为当前上下文,它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。如果没有当前方法(或该方法不属于任何其它对象),则是指全局对象。也就是说,this代表调用该方法对象的引用。正是这种情况如果我们有许多全局变量那么多于代码的维护和复用将非常的困难。
this的理解:
-
<script>
var name='this_aside'; console.log(this.name); function fn(){ this.name='this_fun'; console.log(this.name); } fn();
</script>
此时的输出: -
<script>
var name='this_aside'; function fn(){ this.name='this_fun'; console.log(this.name); } fn(); console.log(this.name);
</script>
此时的输出:
-
<script>
var name='this_aside'; var obj={ name:'this_obj', showName:function(){ console.log(this.name); } }; function fn2(){ this.name='this_fn2'; } obj.showName(); obj.showName.apply(this); obj.showName.apply(fn2);
</script>
第一个showName()的上下文为obj,而使用apply此时传入的this代表的则是对象,输出的fn2即为对象名:
-
<script>
var name='this_aside'; function fn(){ this.name='this_fun'; this.showName = function () { console.log(this.name); } } var value = new fn(); value.showName(); console.log(this.name);
</script>
通过与java中类似的构造来实现方法的调用,此时构造的this为fn()对象,在fn中这种结构也被称为闭包,输出结果:
减少全局变量污染的问题,也是让代码模块化的一种技巧,使我们的代码复用性更高
-
在开发的应用中只使用一个全局变量
例如:<script> var FIRSTAPP ={ } FIRSTAPP.data ={ data1: 's', data2: 1 } FIRSTAPP.method1 = function name(params) { } FIRSTAPP.method2 ={ addFn: function name(params) { } } </script> 这时的FIRSTAPP就成为了我们网页或者应用的一个基本容器。
-
如this里面提到的闭包,使用闭包来进行信息的隐藏也能达到减少全局变量的污染。
这是本次一个月的js学习分享,望有更多人提意见共同成长。