Javascript 筆記與總結(1-4)this

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.