標籤:
js 中函數的 4 種調用方式:
① 作為普通函數來調用,this 的值指向 window,準確地說,this 為 null,被解釋成為 window。在 ECMAScript5 標準中,如果 this 為 null,則解釋成 undefined
<script>function t(){ this.x = ‘hello‘;}t();alert(window.x);</script>
彈出:hello
② a.作為對象的方法來調用,this 指向方法的調用者,即該對象
<script>var obj = {x:‘hello‘,y:‘world‘,t:function(){alert(this.x)}};obj.t();</script>
彈出:hello
b.
<script>var obj = {x:‘hello‘,y:‘world‘,t:function(){alert(this.x)}};var dog = {x:‘wang‘};dog.t = obj.t;dog.t();</script>
彈出:wang
作為方法調用時,this 指向其調用那一刻的調用者,即母體對象,不管被調用函數,聲明時屬於方法還是函數
c.
<script>var obj = {x:‘hello‘,y:‘world‘,t:function(){alert(this.x)}};var dog = {x:‘wang‘};dog.t = obj.t;dog.t();show = function(){ alert(‘show ‘+this.x);}dog.t = show;dog.t();</script>
d.
<script>var obj = {x:‘hello‘,y:‘world‘,t:function(){alert(this.x)}};var dog = {x:‘wang‘};dog.t = obj.t;dog.t();show = function(){ alert(‘show ‘+this.x);}dog.t = show;dog.t();</script>
彈出:show wang
③ 作為建構函式調用時
js 中沒有類的概念,建立對象使用建構函式來完成,或者直接用 json 格式{} 來寫對象
<script>function Dog(name,age){ this.name = name; this.age = age; this.bark = function(){ alert(this.name); }}var dog = new Dog(‘妞妞‘,2);dog.bark();</script>
彈出:妞妞
new Dog 發生了一下幾個步驟:
a. 系統建立Null 物件{},(Null 物件 construct 屬性指向 Dog 函數)
b. 把函數的 this 指向該Null 物件
c. 執行該函數
d. 返回該對象
例:
<script>function Robit(){ this.name = ‘瓦力‘; return ‘wali‘;}var robit = new Robit();console.log(robit);</script>
這段代碼將輸出?
答案:
Robit {name: "瓦力"}
輸出的是 Robit 對象,因為函數作為建構函式運行時,return 的值是忽略的,依然返回對象(return 無意義)。
④ 函數通過 call,apply 調用
文法格式:函數.call(對象,參數1,參數2...參數n);
<script>function t(num){ alert(‘我的年齡是 ‘+this.age); alert(‘雖然我看起來像 ‘+(this.age+num));}var human = {name:‘迭戈.科斯塔‘,age:27};human.t = t;human.t(10);</script>
彈出:我的年齡是 27
彈出:雖然我看起來像 28
接下來,不把 t 賦為 human 的屬性,也能把 this 指向 human
<script>function t(num){ alert(‘我的年齡是 ‘+this.age); alert(‘雖然我看起來像 ‘+(this.age+num));}var giroud = {name:‘Giroud‘,age:28};t.call(giroud,-5);</script>
彈出:我的年齡是 28
彈出:雖然我看起來像 23
【分析】:
fn.call(對象,參數1,參數2...參數n);
運行如下:
a. fn 函數中的 this 指向對象 obj
b. 運行 fn(參數1,參數2...參數n)
Javascript 筆記與總結(1-4)this