JavaScript Function.apply() 函數詳解

來源:互聯網
上載者:User

標籤:樣本   code   apply   cal   指定   http   相同   apply()   全域   

文法
functionObject.apply( [ thisObj [, argsArray ]] )

apply()函數用於調用當前函數functionObject,並可同時使用指定對象thisObj作為本次函數執行時函數內部的this指標引用。

該函數屬於Function對象,所有主流瀏覽器均支援該函數。

參數
參數 描述
thisObj 可選/Object類型指定執行functionObject函數時,函數內部this指標引用的對象。
argsArray 可選/Array|argumens對象調用functionObject函數時所傳入的參數數組或arguments對象。

 

 

 

如果提供了argsArray參數,則該參數必須是一個數組,或者arguments對象。數組中的每個元素(arguments對象中的每個屬性0...n)將按照順序作為參數傳入該函數。

如果提供了argsArray參數,則必須提供thisObj參數。

備忘:該函數與Function對象的call()函數作用相同,只不過call()函數是將Function對象的參數一個個分別傳入,apply()函數是將Function對象的參數以一個數組或arguments對象的形式整體傳入。

傳回值

apply()方法的傳回值為任意類型,其傳回值取決於當前functionObject對象的傳回值。

樣本&說明
name = "張三";age = 18;function test(){    document.writeln(this);    document.writeln(this.name);    document.writeln(this.age);     };// 全域函數內部的this預設為全域對象windowtest(); // [object Window] 張三 18var obj = {name: "李四", age: 20};// 更改內部的this指標引用對象為objtest.apply(obj); // [object Object] 李四 20function foo(a, b){    document.writeln(this.name);        document.writeln(a);        document.writeln(b);    }// 改變this引用為obj,同時傳遞兩個參數foo.apply(obj, [12, true]); // 李四 12 truefunction bar(){    var o = {name: "王五"};    // 調用foo()函數,並改變其this為對象o,傳入當前函數的參數對象arguments作為其參數    foo.apply(o, arguments);    }bar("CodePlayer", "www.365mini.com"); // 王五 CodePlayer www.365mini.com

 

JavaScript Function.apply() 函數詳解

聯繫我們

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