1. 程式人生 > 程式設計 >原生js如何實現call,apply以及bind

原生js如何實現call,apply以及bind

1、實現call

步驟:

  1. 將函式設為物件的屬性;
  2. 指定this到函式,並傳入給定引數執行函式;
  3. 執行之後刪除這個函式;
  4. 如果不傳入引數,預設指向window;
Function.prototype.mycall = function (context,...args) {
    //判斷是否為函式,如果不是函式,則報錯
    if (typeof this !== "function") {
        throw new Error("不是函式");
    }
    context = context || window;
    context.fn = this;
    const res = context.fn(...args);
    delete context.fn;
    return res;
}

  測試程式碼:

var name = "李輝",age = 25;
var obj = {
    name: "周果",objAge: this.age,myFun: function (fm,to) {
        console.log(`名字:${this.name},年齡:${this.age},來自:${fm},去往:${to}`)
    }
};
var person = {
    name: "弟弟",age: 12,};

Function.prototype.mycall = function (context,...args) {
    //判斷是否為函式,如果不是函式,則報錯
    if (typeof this !== "function") {
        throw new Error("不是函式");
    }
    context = context || window;
    context.fn = this;
    const res = context.fn(...args);
    delete context.fn;
    return res;
}

obj.myFun.mycall(person,"成都","仁壽"); //名字:弟弟,年齡:12,來自:成都,去往:仁壽

2、實現apply

Function.prototype.myApply = function (context,...args) {
    //判斷是否為函式,如果不是函式,則報錯
    if (typeof this !== "function") {
        throw new Error("不是函式");
    }
    context = context || winhttp://www.cppcns.comdow;
    context.fn = this;
    args = args && args[0] || [];
    const result = context.
程式設計客棧
fn(...args); delete context.fn; return result; }

  測試程式碼:

obj.myFun.myApply(person,["成都","仁壽"]); //名字:弟弟,年齡:12,來自:成都,去往:仁壽

3、實現bind

  bind()方法主要就是將函式繫結到某個物件,bind()會建立一個函式,函式體內的this物件的值會被繫結到傳入bind()中的第一個引數的值。

  方法1:使用apply

Function.prototype.myBind = function () {
    let self = this; //儲存原函式
    let context = [].shift.call(arguments); //儲存需要繫結的this上下文
    let args = [...arguments]; //將傳入的剩餘引數轉換成陣列
    return function () {                 //返回一個新的函式
        self.apply(context,[].concat.call(args,[...arguments]));
    }
}

  ES6簡http://www.cppcns.com化一下:

Function.prototype.myBind = function (context,...args1) {
        return (...args2) => {  //返回箭頭函式,this繫結呼叫這個方法的函式物件
            context = context ZpOfcppk|| window;
            return this.apply(context,args1.concat(args2));//合併引數
        }
    }

  方法2:不使用call以及apply

  將上面的程式碼和js手寫實現apply的程式碼合併一下:

Function.prototype.myBind = function (context,...args1) {
    return (...args2) => {  //返回箭頭函式,this繫結呼叫這個方法的函式物件
        context = context || window;
        context.fn = this;
        const args = args1.concat(args2);
        const res = context.fn(...args);
        delete context.fn;
        return res;
    }
}

  測試程式碼:

obj.myFun.myBind(person,"仁壽")();//名字:弟弟,年齡:12,來自:成都,去往:仁壽

以上就是原生js如何實現call,apply以及bwww.cppcns.comind的詳細內容,更多關於js實現call,apply以及bind的資料請關注我們其它相關文章!