JS手写apply、call、bind方法

一、js手写call:隐式绑定改变this
Function.prototype.customCall = function (thisArg, ...args) {
    // 1、获取被调用的函数
    const fn = this; // 这里的this指向sum

    // 2、绑定this,将thisArg转成对象类型(防止传入非对象类型)
    thisArg = thisArg ? Object(thisArg) : window;
    thisArg.fn = fn;

    // 3、执行函数
    const result = thisArg.fn(...args);
    delete thisArg.fn;

    // 4、返回执行结果
    return result;
};

function sum (num1, num2) {
    console.log('sum函数', this, num1, num2, num1 + num2); // sum函数 String{'abc', fn: ƒ} 10 20 30
    return num1 + num2;
}

sum.customCall('abc', 10, 20);
二、js手写apply:隐式绑定改变this
Function.prototype.customapply = function (thisArg, args) {
    // 1、获取被执行的函数
    const fn = this; // 这里的this指向sum函数

    // 2、绑定this
    thisArg = thisArg ? Object(thisArg) : thisArg; // 处理thisArg为Number/null/undefined的情况
    thisArg.fn = fn;

    // 执行函数
    const result = args ? thisArg.fn(...args) : thisArg.fn(); // args可能为undefined
    delete thisArg.fn;

    // 返回执行结果
    return result;
};

function sum(num1, num2) {
    console.log('sum被调用', this, num1, num2, num1 + num2); // sum被调用 String{'abc'} 10 20
    return num1 + num2;
}

function sum1(num) {
    console.log('sum1被调用', this, num); // sum1被调用 String{'abc', fn: ƒ} 10
    return num;
}

function sum2() {
    console.log('sum2被执行');
}

sum.customapply('abc', [10, 20]); // 隐式调用
sum1.customapply('abc', [10]);
sum2.customapply('abc');
三、js手写bind:隐式绑定改变this
Function.prototype.custombind = function (thisArg, ...args) {
    // 1、获取被调用的函数
    const fn = this;

    // 2、绑定this
    thisArg = thisArg ? Object(thisArg) : window;
    const retFunc = function (...extraArgs) {
        thisArg.fn = fn;
        const result = thisArg.fn(...args, ...extraArgs); // 对两次传入的参数进行合并
        delete thisArg.fn;
        return result;
     };

    // 3、直接返回方法,且这个方法绑定了执行参数
    return retFunc;
};

function sum(num1, num2) {
    console.log('sum被调用了', this, num1, num2, num1 + num2);
    return num1 + num2;
}

sum.custombind('abc', 10)(20);

另一种手写bind

Function.prototype.customBind = function() {
    // 获取要被执行的函数
    const fn = this;

    // 获取this
    let thisArg = Array.prototype.shift.call(arguments);
    thisArg = thisArg ? Object(thisArg) : window; // 必须,要保证thisArg是个Object

    // 获取参数
    const args = Array.prototype.slice.call(arguments);

    return function() {
      const extraArgs = Array.prototype.slice.call(arguments);
      // 绑定this
      thisArg.fn = fn;
      thisArg.fn(...args, ...extraArgs);
    };
}

function sum (num1, num2) {
    const result = num1 + num2;
    console.log('sum被调用', this, num1, num2, result);
    return result;
}

sum.customBind('abc', 10)(20); // sum被调用 String{'abc', fn: ƒ} 10 20 30
四、认识arguments:传递给函数的参数的类数组(array-like)对象

类数组对象:长的像一个数组,实际上是一个对象
1、拥有数组的一些特性,例如length、或可以通过index索引来访问
2、没有数组的一些方法,例如forEach、map等

// 认识arguments
 function sum(num1, num2, num3) {
    // 打印arguments
    console.log(arguments); // Arguments(3)[1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]

    // 常见的对arguments的操作有三个:
    // 1、获取参数长度
    console.log(arguments.length); // 3

    // 2、根据索引值获取某一个参数
    console.log(arguments[0]); // 1

    // 3、callee获取当前arguments所在的函数
    console.log(arguments.callee); // function sum(num1, num2, num3) {}
}
sum(1, 2, 3);
// 类数组转数组
function sum(num1, num2, num3) {
    // 方法一:自己遍历
    // const newArr = [];
    // for (let i = 0; i < arguments.length; i++) {
    //   newArr.push(arguments[i] * 2);
    // }
    // return newArr;

    // 方法二:slice(借助slice内部的遍历)
    // const newArr = Array.prototype.slice.call(arguments);
    // 或
    // const newArr = [].slice.call(arguments);
    // return newArr;

    // 方法三:ES6的from方法
    // const arr = Array.from(arguments);
    // return arr.map(v => v * 2);

    // 方法四:展开运算符
    const arr = [...arguments];
    return arr.map(v => v * 2);
}
sum(1, 2, 3);
// 箭头函数中没有arguments,会去上层作用域找
const hello = () => {
    // console.log(arguments); // arguments is not defined
};

const hi = function () {
    const fn = () => {
        console.log(arguments); // Arguments[123, callee: ƒ, Symbol(Symbol.iterator): ƒ]
    };
    return fn();
};

hello();
hi(123);
五、bind的一些面试题

       bind()方法主要就是将函数绑定到某个对象,bind()会创建一个函数,函数体内的this对象的值会被绑定到传入bind()中的第一个参数的值,例如:f.bind(obj),实际上可以理解为obj.f(),这时f函数体内的this自然指向的是obj;

  var a = {
    b: function() {
      var func = function() {
        console.log(this.c);
      }
      func();
    },
    c: 'hello'
  }
  a.b(); // undefined 这里的this指向的是全局作用域
  console.log(a.c); // hello
  var a = {
    b: function() {
      var _this = this; // 通过赋值的方式将this赋值给that
      var func = function() {
        console.log(_this.c);
      }
      func();
    },
    c: 'hello'
  }
  a.b(); // hello
  console.log(a.c); // hello
// 使用bind方法一
  var a = {
    b: function() {
      var func = function() {
        console.log(this.c);
      }.bind(this);
      func();
    },
    c: 'hello'
  }
  a.b(); // hello
  console.log(a.c); // hello

// 使用bind方法二
  var a = {
    b: function() {
      var func = function() {
        console.log(this.c);
      }
      func.bind(this)();
    },
    c: 'hello'
  }
  a.b(); // hello
  console.log(a.c); // hello
// 分析:这里的bind方法会把它的第一个实参绑定给f函数体内的this,所以里的this即指向{x:1}对象;
// 从第二个参数起,会依次传递给原始函数,这里的第二个参数2即是f函数的y参数;
// 最后调用m(3)的时候,这里的3便是最后一个参数z了,所以执行结果为1+2+3=6
// 分步处理参数的过程其实是一个典型的函数柯里化的过程(Curry)
  function f(y,z){
    return this.x+y+z;
  }
  var m = f.bind({x:1},2);
  console.log(m(3)); // 6
// 分析:直接调用a的话,this指向的是global或window对象,所以会报错;
// 通过bind或者call方式绑定this至document对象即可正常调用
  var a = document.write;
  a('hello'); // error
  a.bind(document)('hello'); // hello
  a.call(document,'hello'); // hello
// 实现预定义参数
// 分析:Array.prototype.slice.call(arguments)是用来将参数由类数组转换为真正的数组;
  function list() {
    return Array.prototype.slice.call(arguments);
  }
  var list1 = list(1, 2, 3); // [1,2,3]
// 第一个参数undefined表示this的指向,第二个参数10即表示list中真正的第一个参数,依次类推
  var a = list.bind(undefined, 10);
  var list2 = a(); // [10]
  var list3 = a(1, 2, 3); // [10,1,2,3]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容

  • 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行(line),也就是一...
    悟名先生阅读 4,057评论 0 13
  • 函数和对象 1、函数 1.1 函数概述 函数对于任何一门语言来说都是核心的概念。通过函数可以封装任意多条语句,而且...
    道无虚阅读 4,348评论 0 5
  • 函数只定义一次,但可能被执行或调用任意次。JS函数是参数化的,函数的定义会包括一个称为形参的标识符列表,这些参数在...
    PySong阅读 820评论 0 0
  • 依旧低飞的蜻蜓 在沟渠积水里映出自己 它们来不及逃跑或者飞高 阳光就散开了 空气里被一扫而空 干净的一览无余,大概...
    鹿原先生和蓬蒿阅读 947评论 6 30
  • 老师泄题,学校乱收费,刻意而为的打手,一切看分数的社会大势,甚至那些利用琳的有钱人,他们被遣返回国以后,也可以过着...
    张十九L阅读 271评论 0 0