JS明確指定函數的接受者

來源:互聯網
上載者:User

標籤:code   c   ext   a   使用   cti   

由於方法和值為對象的屬性值沒什麼區別,因此很容易提取對象的方法作為回呼函數直接傳遞給高階函數。但這也很容易忘記應明確指定方法的接受者。例如,一個字串緩衝對象使用數組來儲存字串。

var buffer = {    entries: [],    add: function(args) {        this.entries.push(args);    },    concat: function() {        return this.entries.join(‘‘);    }};var arr = [‘alert‘, ‘-‘, ‘123‘];// error: entries is undefinedarr.forEach(buffer.add);buffer.concat();

方法的接受者取決於它是如何被調用的。forEach方法的實現使用全域對象作為預設的接受者。由於全域對象沒有entries屬性,因此這段代碼拋出了一個錯誤。

在回呼函數中執行方法
var arr = [‘alert‘, ‘-‘, ‘123‘];arr.forEach(function() {    buffer.add(arr);});buffer.concat();

該方法建立一個顯示地以buffer對象方法的方式調用add()。

使用bind()返回一個指定接受者的函數

建立一個函數用來實現綁定其接受者到一個指定對象是常見的。

arr = [‘alert‘, ‘-‘, ‘123‘];arr.forEach(buffer.add.bind(buffer));buffer.concat();

注意,bind()返回的是一個新的函數而不是修改buffer.add函數。這意味著bind方法是安全的。

其實forEach()允許調用者提供一個可選的參數作為回呼函數的接受者。arr.forEach(buffer.add, buffer)。

相容沒有實現forEach()方法的瀏覽器

if(typeof Function.prototype.forEach !== ‘function‘) {    Function.prototype.bind = function(context) {        return this.apply(context, [].slice.call(arguments, 1));    }}

聯繫我們

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