<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學習分享,望有更多人提意見共同成長。