javascript中call apply 的應用情境,javascriptapply

來源:互聯網
上載者:User

javascript中call apply 的應用情境,javascriptapply

在一些jQuery外掛程式中經常看到類似 callback.call(xxx,xxx) 雖然看到書上有介紹 說call和apply函數可以改變範圍,但還是無法非常透徹的理解改變範圍主要是為瞭解決什麼問題,有沒有替代方案,或者 這2個函數主要為瞭解決什麼問題,應用情境,何時使用最合適,每次讀到這樣的代碼就暈了,一下子從線性閱讀中跳出去了,感覺有點繞

call和apply的作用很簡單,就是改變上下文,適用情境太多了,雖然有時候只是為了“美觀”,下面幾個是我常用的。

1.

複製代碼 代碼如下:Object.prototype.toString.call(Obj)

用來判斷 Obj 的類型

arguments 雖然和Array 很像,但是他沒有Array的push之類的方法,怎麼辦?
Array.prototype.push.call(arguments)

3.Javascript 沒有私人方法的概念,想用閉包實現

(function () {  var Person = function () {    this.doSomeThing = function () {      _privateFunction.call(this);    }  }  var _privateFunction = function () {  }  window.Person = Person;}).call(window);

差不多就是這個意思,callback的時候,當你希望你的callback中的上下文是當前內容相關的時候,也可以用call或者apply,有什麼好處呢?

這個時候你的callback 裡面的this 就是指代當前上下文。例如一個類Person,然後他的方法 say 有一個callback的參數,如果這個callback是通過普通的括弧來執行的話,那在這個callback裡面執行person的其它方法還需要用person.other 來實現,但是切換上下文之後,就是this.other搞定~代碼對比如下:

var Person = function(){};Person.prototype.say = function(callback){  callback();};Person.prototype.other = function(){};var vincent = new Person();vincent.say(function(){  vincent.other();});

用了call的:

var Person = function(){};Person.prototype.say = function(callback){  callback.call(this);};Person.prototype.other = function(){};var vincent = new Person();vincent.say(function(){  this.other();});

以上所述就是本文的全部內容了,希望大家能夠喜歡。

聯繫我們

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