apply() 方法調用一個函數, 其具有一個指定的this值,以及作為一個數組(或類似數組的對象)提供的參數fun.apply(thisArg, [argsArray])
apply 和 call 基本類似,他們的區別只是傳入的參數不同。
apply 和 call 的區別是 call 方法接受的是若干個參數列表,而 apply 接收的是一個包含多個參數的數組。
bind()方法創建一個新的函數, 當被調用時,將其this關鍵字設置為提供的值,在調用新函數時,在任何提供之前提供一個給定的參數序列。
call做了什么:
將函數設為對象的屬性
執行&刪除這個函數
指定this到函數并傳入給定參數執行函數
如果不傳入參數,默認指向為 window
```
//實現一個call方法:
Function.prototype.myCall = function(context) {
//此處沒有考慮context非object情況
context.fn = this;
let args = [];
for (let i = 1, len = arguments.length; i < len; i++) {
args.push(arguments[i]);
}
context.fn(...args);
let result = context.fn(...args);
delete context.fn;
return result;
};
```
```
/ 模擬 apply
Function.prototype.myapply = function(context, arr) {
var context = Object(context) || window;
context.fn = this;
var result;
if (!arr) {
result = context.fn();
} else {
var args = [];
for (var i = 0, len = arr.length; i < len; i++) {
args.push("arr[" + i + "]");
}
result = eval("context.fn(" + args + ")");
}
delete context.fn;
return result;
};
```
實現bind要做什么
返回一個函數,綁定this,傳遞預置參數
bind返回的函數可以作為構造函數使用。故作為構造函數時應使得this失效,但是傳入的參數依然有效
```
// mdn的實現
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
// this instanceof fBound === true時,說明返回的fBound被當做new的構造函數調用
return fToBind.apply(this instanceof fBound
? this
: oThis,
// 獲取調用時(fBound)的傳參.bind 返回的函數入參往往是這么傳遞的
aArgs.concat(Array.prototype.slice.call(arguments)));
};
// 維護原型關系
if (this.prototype) {
// Function.prototype doesn't have a prototype property
fNOP.prototype = this.prototype;
}
// 下行的代碼使fBound.prototype是fNOP的實例,因此
// 返回的fBound若作為new的構造函數,new生成的新對象作為this傳入fBound,新對象的__proto__就是fNOP的實例
fBound.prototype = new fNOP();
return fBound;
};
}
```
```
// 簡單版
Function.prototype.myBind = function(context,...arg){
// this ---> fn
var _this = this;
return function(...ary){
// _this(...arg)
return _this.apply(context,arg.concat(ary))
}
}
```
- 介紹
- 原生JS
- 1.ES6的新特性
- 2.JS的數據類型
- 3.定義函數的方法
- 4.JS作用域的理解
- 5.閉包的理解
- 6.數組去重
- 7.原型及原型鏈
- 8.Object.create的作用
- 9.new的執行過程是怎么回事
- 10.call,apply,bind三者的區別
- 11.實現類的繼承
- 12.談談你對this指向的理解
- 13.DOM
- 14.JS的異步編程
- 15.正則
- http&ajax
- 1.TCP/IP的三次握手和四次揮手
- 2.http常用狀態碼(http-status-code):
- 3.從瀏覽器輸入URL按回車到頁面顯示都發生了什么?
- 4.HTTPS和HTTP的區別
- 5.瀏覽器緩存?
- 6.ajax四步
- 7.一般我們再攔截器中都會寫什么代碼?
- 8.get請求和post請求有什么區別?什么時候使用post?
- 9.Cookie 和 Session 的區別?
- 10.Token 相關
- 11.什么是同源策略?