JS中的call/apply/bind

來源:互聯網
上載者:User

標籤:

<script>        var obj = {            a:1        }            var a = 2;                function test(a)        {            alert(a);            alert(this.a);        }        </script>

 

1.test(3);

  結果:"3"、"2";

  解釋:實參3傳遞給形參a,函數內部的形參a覆蓋全域變數a,所以第一個為3,函數中this為window對象,所以this.a為2

2.test.call(thisObject,param1,param2...);

    thisObject:更改test函數中this的指向;

    param:為test函數傳遞參數,以字串的形式

  test.call(null);

    結果:"undefined","2";

    解釋:test(a)執行時,並沒有參數傳遞過來,a為undefined,由於傳遞thisObject是null,在執行test函數時,瀏覽器把thisObejct沒有指向時,一律指向window對象,所以第二個彈出為2。同樣的test.call(undefined);的結果同上;

3.test.call(null,3);

  結果:"3","2";

4.test.call(obj);

  結果:"undefined","1";

5.test.call(obj,3);

  結果:"3","1";

6.test.apply(thisObject,[param1,param2....]);

  除了給函數傳遞參數的形式是以數組,其他的和call(thisObject,param1,param2...);

7.test.bind(thisObject,param1,param2...)

  thisObject:更改this指向

  param:參數

這個方法返回this更改指向,且獲得實參的函數對象

var ss = test.bind(null);

ss();

結果:"undefined","2"

var ss = test.bind(obj);

ss();

結果:"undefined","1";

var ss = test.bind(obj,3);

ss();

結果:"3","2";

當函數有多個參數時:

function test(a,b,c){    alert(a+":"+b+":"+c);}        var ss = test.bind(obj,3);ss(4,5,6);

結果為:3,4,5卻不是4,5,6;因為在bind的時候,就將3賦值給了a,在ss(4,5,6)時,6並未賦值給c;

arguments中儲存的值為3,4,5,6;


JS中的call/apply/bind

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.