<script>javascript
var name='this_aside'; console.log(this.name); function fn(){ this.name='this_fun'; console.log(this.name); } fn();
</script>
此时的输出:html
<script>java
var name='this_aside'; function fn(){ this.name='this_fun'; console.log(this.name); } fn(); console.log(this.name);
</script>闭包
此时的输出:app
<script>ide
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中这种结构也被称为闭包,输出结果:this
在开发的应用中只使用一个全局变量
例如:
<script> var FIRSTAPP ={ } FIRSTAPP.data ={ data1: 's', data2: 1 } FIRSTAPP.method1 = function name(params) { } FIRSTAPP.method2 ={ addFn: function name(params) { } } </script> 这时的FIRSTAPP就成为了咱们网页或者应用的一个基本容器。
如this里面提到的闭包,使用闭包来进行信息的隐藏也能达到减小全局变量的污染。
这是本次一个月的js学习分享,望有更多人提意见共同成长。