再嚼一嚼call,apply,bind

Call、apply、bind、的區別

這三個都是爲了改變this指向而存在的,使用上會有一些不一樣,先來看一張圖javascript

call的使用

1var a = {
2    des:'可愛的你'
3}
4function fn(age,name{
5        console.log(age,name,this.des)
6}
7//執行
8fn.call(a,18,'支付寶');
複製代碼
執行結果
一塊兒來仿寫一個call
 1Function.prototype.myCall = function(context{
2    //拿到第一個參數,用戶傳的對象
3  var context = context || window;
4  //拿到除了第一個對象的,其餘剩餘參數
5  var args = [...arguments].slice(1);
6  //把當前函數掛載在傳過來的對象上
7  context.fn = this;
8  //執行掛載的函數
9  var result = context.fn(...args);
10  //刪除掛載對象
11  delete context.fn;
12  //返回執行結果
13  return result;
14}
複製代碼
執行結果

看完call,再看下apply,原理是同樣的

使用方式
1var a = {
2  des'帥氣的你'
3}
4function fn (age, name{
5    console.log(age, name, this.des)
6}
7//執行,apply第二個參數是一個數組
8fn.apply(a, [18,'微信'])
複製代碼
執行結果
一樣咱們一塊兒來仿一個apply的實現
 1Function.prototype.myApply = function(context{
2      //獲取第一個參數對象
3        var context = context || window;
4      //獲取除來第一個參數,其餘剩餘參數
5      var args = arguments.slice(1)[0];
6      //掛載當前函數到傳過來的對象上
7      context.fn = this;
8      //執行函數
9      var result = context.fn(...args);
10      //刪除掛載對象
11      delete context.fn;
12      //返回結果
13      return result;
14}
複製代碼
執行結果

bind的使用

1let a = {
2    des'完美的你'
3}
4function fn (age, name{
5        console.log(age,name,this.des)
6}
7//執行,⚠️bind返回是一個函數,因此須要再加()執行
8fn.bind(a,18,'餘額寶')();
複製代碼
執行結果
一樣咱們仿寫一個bind實現
 1Function.prototype.Mybind = function (context{
2        //首先須要判斷調用方式是否正確
3      if(typeof this !== 'function') {
4          throw new TypeError('Error');
5    }
6      //存儲下當前函數
7      var _this = this;
8      //獲取參數
9      var args = [...arguments].slice(1);
10      //返回一個函數
11      return function F ({
12      //須要考慮是否被new的狀況
13      if(this instanceof F) {
14            return new _this(...args,...arguments)
15      }
16      //不然經過apply返回結果
17      return _this.apply(context,args.concat(...arguments));
18        }
19}
複製代碼
執行結果

~~天天分享一點點,和你共同進步~~java

相關文章
相關標籤/搜索