在JS開發中,經常使用this,我覺得有必要對this進行總結一下。
定義
this 代表目前正在執行某個方法的對象,如果沒有目前方法(或該方法不屬于任何其它對象),則是指全局對象。也就是說,this代表調用該方法對象的引用。
全局範圍中的this
全局裡面的this,比較好了解,一般不容易出錯。首先,看看下面代碼,會輸出什麼呢?
<script type="text/javascript">
console.log(this==window);
console.log(this);
</script>
直接結果如下:
這說明,如果沒有目前方法(或該方法不屬于任何其它對象),則this是指全局對象window。
于是可以得出,輸出一個全局變量,可以采取下面幾種方式
var name="dqs";
console.log(name);
console.log(window['name']);
console.log(window.name);
console.log(this['name']);
console.log(this.name);
函數裡面的this
函數裡面的this,取決于函數的調用方式,調用方式不一樣,那麼裡面的this也就會不一樣。
直接以函數形式調用
直接以函數形式調用,函數裡的this,代表全局對象,即window。
<script type="text/javascript">
function fn(){
console.log(this);
}
fn();
</script>
結果如下:
以全局對象的方法形式調用
以全局對象的方法形式調用,此時this,也代表全局對象,即window。
<script type="text/javascript">
function fn(){
console.log(this);
}
fn();
console.log(this.fn());
console.log(window.fn());
</script>
借助call或者apply函數調用
借助call或者apply函數調用時候,此時this代表指定的對象。
<script type="text/javascript">
var obj={name:'obj_dqs'};
function fn(){
console.log(this);
}
function fn2(){
this.name='fn_dqs';
}
fn.call(obj)//此時this代表obj
fn.call(fn2)//此時this代表fn2
</script>
結果如下:
以構造函數形式調用
當以構造函數形式調用時候,此時this,代表建立的對象。
<script type="text/javascript">
var name='window_dqs';
function fn(){
this.name='fn_dqs';
this.showName=function(){
console.log(this.name);
}
console.log(this);
}
var p=new fn();
</script>
結果如下圖:
with中的this
在分析with(obj)中的this時候,我們需要分析其所在範圍。如果是在函數中的this,代表obj,如果是全局範圍變量中,則代表window
<script type="text/javascript">
var name='window_dqs';
var obj={
name:'obj_dqs',
showName:function(){
console.log(this);
}};
function showName(){
console.log(this);
}
with(obj){
console.log(this);
showName();
}
showName();
</script>
輸出結果如下
綜合練習
如果能很清楚的,說出輸出結果,那麼this這一塊就可以說是掌握了。
例題1
<script type="text/javascript">
var name='window_dqs';
var obj={
name:'obj_dqs',
showName:function(){
console.log(this.name);
}};
function fn(){
console.log(this);
}
function fn2(){
this.name='fn_dqs';
}
obj.showName();
obj.showName.apply(this);
obj.showName.apply(fn2);
</script>
輸出結果如下:
例題2
<script type="text/javascript">
var name='window_dqs';
function fn(){
this.name='fn_dqs';
this.showName=function(){
console.log(this.name);
}
console.log(this);
}
function fn2(){
this.name='fn_pps';
this.showName=function(){
console.log(this.name);
}
console.log(this);
}
var p=new fn();
fn2.apply(p);
p.showName();
var obj={};
fn2.apply(obj);
obj.showName();
</script>
輸出結果如下:
例題3
<script type="text/javascript">
var name='window_dqs';
var obj={
name:'json_dqs',
showName:function(){
console.log(this.name);
return function(){
console.log(this.name);
}
}
}
var p=obj.showName();
obj.showName()();
p.call(obj);
</script>
結果如下