每天一個JavaScript執行個體-apply和call的用法,javascript-apply

來源:互聯網
上載者:User

每天一個JavaScript執行個體-apply和call的用法,javascript-apply

<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>每天一個JavaScript執行個體-apply和call的用法</title><script>function Person(name,age){   //定義一個類,人類      this.name=name;     //名字      this.age=age;       //年齡     this.sayhello=function(){console.log("hello")};} function Print(){            //顯示類的屬性     this.funcName="Print";     this.show=function(){              var msg=[];        for(var key in this){             if(typeof(this[key])!="function"){                msg.push([key,":",this[key]].join(""));            }        }         console.log(msg.join("-----"));    };} function Student(name,age,grade,school){    //學生類     Person.apply(this,arguments);    Print.apply(this,arguments);    this.grade=grade;                //年級     this.school=school;                 //學校 } var p1=new Person("jake",10);p1.sayhello();var s1=new Student("tom",13,6,"清華小學");s1.show();s1.sayhello();console.log(s1.funcName);</script></head><body></body></html>


javascript中 apply()跟call()方法分別指的是什 有什不同

call, apply都屬於Function.prototype 原型的一個方法,它是JavaScript引擎內在實現的,因為屬於Function.prototype,所以每個Function對象執行個體,也就是每個方法都有call, apply屬性.既然作為方法的屬性,那它們的使用就當然是針對方法的了.這兩個方法是容易混淆的,因為它們的作用一樣,只是使用方式不同.
相同點:兩個方法產生的作用是完全一樣的
不同點:方法傳遞的參數不同
 
javascript call apply 不理解 教

call和apply有個用處,就是可以用變數作為函數名稱來調用。比如函數的回呼函數。具體用法是:被執行函數.call(a,b,c...),其中a是在被執行函數中this需要指定的對象,可以為null,其他參數作為被執行函數的參數。apply用法類似,只不過第二個參數是數組。
舉例說明:
function doPost(url,param,callback){
//這裡處理post請求
var str = xhr.responseText;
callback.apply(this,[str]);//相當於調用了callback(str);並把callback中的this設定為doPost對象
}
 

聯繫我們

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