1. 程式人生 > >JS中bind方法,apply方法,call方法的實現

JS中bind方法,apply方法,call方法的實現

先分析下3個方法的作用

  • 改變this的指向。
  • 傳入引數。
  • call apply返回函式結果, bind 返回新函式

我們先從call開始

改變this指向

首先我們知道,物件上的方法,在呼叫時,this是指向物件的。

ler 0 = {
    fn:function(){
        console.log(this);
    }
}

知道了這點,我們就可以實現改變this的指向了。

// 函式原型上新增myCall方法,來模擬call
Function.prototype.myCall = function(obj)
{
// 我們要讓傳入的obj成為,函式呼叫時的this值, obj._fn_ = this; //在obj上新增_fn_屬性,值是this(需呼叫此方法的那個函式物件) obj._fn_(); // 在obj上呼叫函式,那函式的this值就是obj delete obj._fn_; //刪除obj的_fn_的屬性,去除影響。 // _fn_ 只是個屬性名,你可以隨意起名,但是要注意可能會覆蓋obj上本來就有的屬性。 }

下面測試一下。

let test = {
    name:'test',
}
let o = {
    name:'o',
    fn:function
(){
console.log(this.name,...arguments); } } o.fn();// "o" o.fn.call(test);// o.fn.myCall(test)

現在,改變this的值,實現了。

傳入引數

  • 最簡單的實現,ES6
Function.prototype.myCall = function(obj,arguments){
    let obj._fn_ = this;
    obj._fn_(...arguments);
    delete obj._fn_;
}
let test = {
    name:'test'
} let o = { name:'o', fn(){ console.log(this.name,...arguments); } } o.fn();// o o.fn.myCall(test,1,2,3)// 0,1,2,3 o.fn.call(test,1,2,3)// 0,1,2,3

不用ES6就比較麻煩了
* 用eval方法
eval方法,會傳入的字串,當做JS程式碼進行解析,執行。

Function.prototype.myCall = function(obj){
     var arg = [];
     for(let i = 1; i < arguments.length; i++){
        arg.push('arguments['+i+]');
        *******
        // 這裡要push 這行字串 而不是直接push值
        // 因為直接push值會導致一些問題
        // 例如:push一個數組[1,2,3]
        // 在下面 eval呼叫時,進行字串拼接,JS為了將陣列轉換為字串
        // 會去呼叫陣列的toString()方法,變為'1,2,3'就不是一個數組了,相當於是3個引數
        // 而push這行字串,eval方法,執行程式碼會自動去arguments裡獲取值,eval會自動去除陣列的外框。
        ******
     }
     obj._fn_ = this;
     eval('obj._fn_('+arg+')')//字串拼接,JS會呼叫arg陣列的toString方法,這樣就傳入了所有引數。
     delete obj._fn_;
}
// 測試
let test = {
     name:'test',
}
let o = {
    name:'o',
    fn:function(){
       console.log(this.name,...arguments);//這裡把引數顯示一下
    }
}
o.fn(1,['a','b'],3) // "o" 1 ["a","b"] 3
o.fn.call(test,1,['a','b'],3) // "test" 1 ["a","b"] 3
o.fn.myCall(test,1,['a','b'],3) // "test" 1 ["a","b"] 3
// 沒問題

返回函式值

很簡單,變數儲存一下

Function.prototype.myCall = function(obj,...arg){
    let val ;
    obj._fn_ = this;
    val = obj._fn_(...arg);  //不能直接return obj._fn_(...arg) 這樣就不delete屬性了
    delete obj._fn_;
    return val;
}
Function.prototype.myCall = function(obj){
    let arg = [];
    let val ;
    for(let i = 1 ; i<arguments.length ; i++){ // 從1開始
        arg.push( 'arguments[' + i + ']' ) ;
    }
    obj._fn_ = this;
    val = eval( 'obj._fn_(' + arg + ')' ) // 字串拼接,JS會呼叫arg陣列的toString()方法,這樣就傳入了所有引數
    delete obj._fn_;
    return val;
}

傳參檢測

傳入的obj如果是null,undefined應該為window。如果是string,number,boolean應該轉換為物件。
* 介意自己加入一下判斷,為了方便觀看,我就先不加了。

if(obj === null||obj === undefined){
    obj = window;
}else{
    obj = Object(obj);
}

實現apply

其實apply和call差不多,沒多大區別
* 利用已經寫好的myCall來實現

// ES6
Function.prototype.myApply = function(obj,arr){
    let args = [];
    for(let i = 0 ; i<arr.length; i++){
        args.push( arr[i] );
    }
    // 其實直接 ...arr 傳參也可以 但是效果就和aplly有微小差別了
    return this.myCall(obj, ...args);
}
// ES3
Function.prototype.myApply = function(obj,arr){
    let args = [];
    for(let i = 0 ; i<arr.length; i++){
        args.push( 'arr[' + i + ']' );  // 這裡也是push 字串
    }
    return eval( 'this.myCall(obj,' + args + ')' );
}
  • 不用myCall
Function.prototype.myApply = function(obj,arr){
    let args = [];
    let val ;
    for(let i = 0 ; i<arr.length ; i++){
        args.push( 'arr[' + i + ']' ) ;
    }
    obj._fn_ = this;
    val = eval( 'obj._fn_(' + args + ')' ) 
    delete obj._fn_;
    return val
}
  • 測試
Array.apply({},{length:3});
// 返回 [undefined, undefined, undefined]
Array.myApply({},{length:3});
// 返回 [undefined, undefined, undefined
****返回正常****

實現bind

  • ES6+寫好的myApple
Function.prototype.myBind = function(obj,...arg1){ //rest引數
      return (...arg2)=>{  //返回箭頭函式,this繫結呼叫這個方法myBind的函式物件。這個和箭頭函式的指向有關
         return this.myApply(obj,arg1.concat(arg2)) //將引數合併
      }
}
  • ES6
// 其實沒什麼說的
Function.prototype.myBind = function(obj,...arg1){
    return (...arg2) => { 
        let args = arg1.concat(arg2);
        let val ;
        obj._fn_ = this;
        val = obj._fn_( ...args ); 
        delete obj._fn_;
        return val
    }
}

測試下

let test = {
    name:'test'
}
let o = {
    name:'o',
    fn:function(){
        console.log(this.name, ...arguments);  //這裡把引數顯示一下
    }
}
//myBind
b = o.fn.myBind(test,1,2)
b() // "test" 1 2
b(3,4) // "test" 1 2 3 4
// bind
b = o.fn.bind(test,1,2)
b() // "test" 1 2
b(3,4) // "test" 1 2 3 4

三個方法的我寫的程式碼

  • 模擬call
Function.prototype.myCall = function(obj){
    if(obj === null || obj === undefined){
        obj = window;
    } else {
        obj = Object(obj);
    }
    let arg = [];
    let val ;
    for(let i = 1 ; i<arguments.length ; i++){
        arg.push( 'arguments[' + i + ']' ) ;
    }
    obj._fn_ = this;
    val = eval( 'obj._fn_(' + arg + ')' ) 
    delete obj._fn_;
    return val
}
  • 模擬apply
Function.prototype.myApply = function(obj,arr){
    if(obj === null || obj === undefined){
        obj = window;
    } else {
        obj = Object(obj);
    }
    let args = [];
    let val ;
    for(let i = 0 ; i<arr.length ; i++){
        args.push( 'arr[' + i + ']' ) ;
    }
    obj._fn_ = this;
    val = eval( 'obj._fn_(' + args + ')' ) 
    delete obj._fn_;
    return val
}
  • 模擬bind
Function.prototype.myFind = function(obj){
    if(obj === null || obj === undefined){
        obj = window;
    } else {
        obj = Object(obj);
    }
    let _this = this;
    let argArr = [];
    let arg1 = [];
    for(let i = 1 ; i<arguments.length ; i++){  
        arg1.push( arguments[i] );
        argArr.push( 'arg1[' + (i - 1)  + ']' ) ;
    }
    return function(){
        let val ;
        for(let i = 0 ; i<arguments.length ; i++){
            argArr.push( 'arguments[' + i + ']' ) ;
        }
        obj._fn_ = _this;
        console.log(argArr);
        val = eval( 'obj._fn_(' + argArr + ')' ) ;
        delete obj._fn_;
        return val
    };
}

作者:泡沫的快樂
連結:https://www.jianshu.com/p/3b69fb0d4c2f
來源:簡書