javascript bind()

來源:互聯網
上載者:User

標籤:

前幾天看到一個面試題,題目是這樣的:
請你說說對javascript中apply,call,bind的理解?
首先apply和call是老生常談的東西,但是對於bind,我愣了下,因為這個詞是jquery中使用頻率很高的一個方法,用來給DOM元素繫結事件用的。
為了搞清這個陌生又熟悉的bind,google一下,發現javascript1.8.5版本中原生實現了此方法,目前IE9+,ff4+,chrome7+支援此方法,opera和safari不支援(MDN上的說明)。
bind的作用和apply,call類似都是改變函數的execute context,也就是runtime時this關鍵字的指向。但是使用方法略有不同。一個函數進行bind後可稍後執行。
例子如下:

複製代碼 代碼如下:
var person = {
name: ‘Andrew‘,
job: ‘web front end developer‘,
gender: ‘male‘,
sayHello: function() {
return ‘Hi, I am ‘ + this.name + ‘, a ‘ + this.job;
}
}
console.log(person.sayHello()); // Hi, I am Andrew, a web front end developer
var anotherGuySayHello = person.sayHello.bind({
name:‘Alex‘,
job: ‘back end C# developer‘
});
console.log(anotherGuySayHello()); // Hi, I am Alex, a back end C# developer


另外帶有參數的例子:

複製代碼 代碼如下:


function add(arg1, arg2, arg3, arg4) {
return arg1 + ‘ ‘ + arg2 + ‘ ‘ + arg3 + ‘ ‘ + arg4;
}
var addMore = add.bind({}, ‘a‘, ‘b‘);
console.log(addMore(‘c‘, ‘d‘)); // a b c d

javascript 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.