1.都可以改變函數的執行上下文,也就是this值;web
2.call() apply()數組
1 function apply(num1, num2){ 2 return sum.apply(this, [num1,num2]); 3 } 4 function call(num1, num2){ 5 return sum.call(this, num1, num2); 6 }
參數的第一部分:執行上下文,就是this;session
參數的第二部分:須要傳遞的參數,能夠是一個,也能夠爲多個;app
apply第二部分須要的是一個數組做爲參數;函數
call第二部分的參數是數組裏面的元素,須要一個一個傳,用逗號隔開;this
可是第二部分都可以傳arguments;es5
若是call和apply的第一個參數寫的是null,那麼this指向的是window對象。spa
1 var a = { 2 user:"zhangsan", 3 fn:function(){ 4 console.log(this);//Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…} 5 } 6 } 7 var b = a.fn; 8 b.apply(null);
3.bind()code
屬於es5中的方法,也是用來實現上下文綁定,可是它是新建立一個函數,稱爲綁定函數,而後把它的上下文綁定到bind()括號中的參數上,而後將它返回;對象
4.bind()與call()、apply()最大的區別:bind()不會當即調用,須要加上()來執行,其餘兩個會直接調用;
bind方法能夠讓對應的函數想何時調就何時調用,而且能夠將參數在執行的時候添加,視狀況而定。
1.第一個參數均是this要指向的對象;
2.都是用來改變函數this對象的指向;
3.均可以繼續傳遞參數.
看代碼:
var person = { name: 'zhangsan', sex: '男', say: function(){ console.log(this.name + ',' + this.sex); } } var other = { name: 'lili', sex: '女', } person.say.call(other);//lili,女 person.say.apply(other);//lili,女 person.say.bind(other)();//lili,女
帶參數形式:
1 var person = { 2 name: 'zhangsan', 3 sex: '男', 4 say: function(school,grade){ 5 console.log(this.name + ',' + this.sex + ';' + school + grade); 6 } 7 } 8 var other = { 9 name: 'lili', 10 sex: '女', 11 } 12 person.say.call(other,'北京大學','2');//lili,女;北京大學2 13 person.say.apply(other,['清華大學','3']);//lili,女;北京大學3 14 person.say.bind(other,'南開大學',4)();//lili,女;北京大學4