自定义call、apply、bind函数

    技术2022-07-15  55

    ES6新增的call、apply、bind方法,用于改变方法的this指向,我们来实现一下它们的基本逻辑:

    自定义 call 函数

    Function.prototype.myCall = function (context) { var context = Object(context) || window; // 传递this指向 context.fn = this; // 传递参数 var args = [...arguments].slice(1); var result = context.fn(...args); delete context.fn; return result; };

    自定义 apply 函数

    Function.prototype.myApply = function (context, args) { var context = Object(context) || window; context.fn = this; var result = ""; // 由于apply的传参方式同call不同 // 原方法的参数是以数组形式传递 // 所以需要判断一下 if (args) { result = context.fn(...args); } else { result = context.fn(); } delete context.fn; return result; };

    自定义 bind 函数

    Function.prototype.myBind = function (context) { if (typeof this !== "function") { // 判断this指向的是否是方法,如果不是抛出类型错误 throw new TypeError("Err"); } var self = this; // bind的参数传递方法有两种 // 1.bind调用时传参 var arg1 = [...arguments].slice(1); const bindFn = function () { // 2.调用bind返回的方法时再传参 var arg2 = [...arguments]; // 拼接bind所有可能的参数 return self.myApply(context, arg1.concat(arg2)); }; // bind方法返回的是一个新方法 return bindFn; };
    Processed: 0.011, SQL: 9