JavaScript解密之旅----call apply bind使用原理及JS手写
发布日期:2021-05-15 00:08:53 浏览次数:13 分类:精选文章

本文共 2634 字,大约阅读时间需要 8 分钟。

文章目录


前言

call apply bind,这三者都是用来改变函数的this对象的指向的。

通俗来讲就是,东风之礼,借来可用

一、使用上的异同

1. 相似之处:

  1. 都是用来改变函数的this对象的指向的。
  2. 第一个参数都是this要指向的对象。
  3. 都可以利用后续参数传参。

2. 不同之处

  1. call 的传参是单个传参
  2. apply 传参是以一个数组的行书
  3. bind 非常特殊,可在对象后追加,也可以在传参数进行输入

二、call详细用法

1. 通俗解释

字面意思是“借用”,“请求”,一个场景:当你十分想抽烟,结果手里没带火机,也没有烟,这时候你需要去借烟和活(虽然是有点过分)

2. 代码案例

var smokeMe = {           name: "没有香烟",        tool: "没有火机",        smoking: function (a, b) {             alert("我在用" + this.tool + "点" + this.name + "==>" + a + b);        },      };      var smokerYou = {           name: "宇宙牌香烟",        tool: "石英火机",      };      smokeMe.smoking.call(smokerYou, "白嫖", "心里美滋滋");

3. Js手写call

  1. 首先context为可选参数,如果不传的话默认上下文是window
  2. 接下来给content创建一个fn属性,并将值设置为需要调用的函数
  3. 因为call可以传入多个参数作为调用函数的参数,所有需要将参数剥离出来
  4. 然后调用函数并将对象上的函数删除
Function.prototype.Mycall = function (val) {           val = val || window;        val.fn = this;        const args = [...arguments].slice(1);        const result = val.fn(...args);        delete val.fn;        return result;      };smokeMe.smoking.Mycall(smokerYou, "白嫖", "心里美滋滋");

apply详细用法

1. 代码案例

使用方法与call一致,传入第二个参数的形式是数组

smokeMe.smoking.apply(smokerYou,["白嫖", "心里美滋滋"]);

2. Js手写apply

Function.prototype.myApply = function (context) {           if (typeof this !== "function") {             throw new TypeError("Error");        }        context = context || window;        context.fn = this;        let result;        if (arguments[1]) {             result = context.fn(...arguments[1]);        } else {             result = context.fn();        }        delete context.fn;        return result;      };      smokeMe.smoking.apply(smokerYou,["白嫖", "心里美滋滋"]);

bind详细用法

1. 代码案例

使用方法与call传参形式也可以,在后面传参也可以

smokeMe.smoking.bind(smokerYou,"白嫖", "心里美滋滋")();    smokeMe.smoking.bind(smokerYou)("白嫖", "心里美滋滋");    smokeMe.smoking.bind(smokerYou,["白嫖", "心里美滋滋"])();    smokeMe.smoking.bind(smokerYou)(["白嫖", "心里美滋滋"]);

2. Js手写bind

Function.prototype.myApply = function (context) {           if (typeof this !== "function") {             throw new TypeError("Error");        }        context = context || window;        context.fn = this;        let result;        if (arguments[1]) {             result = context.fn(...arguments[1]);        } else {             result = context.fn();        }        delete context.fn;        return result;      };   smokeMe.smoking.bind(smokerYou)("白嫖", "心里美滋滋");

综合Demo

      
Document

call apply bind

显示结果区域:(
上一篇:VUE框架基础--------生命周期理解
下一篇:VUE框架应用包---------微信二维码应用

发表评论

最新留言

表示我来过!
[***.240.166.169]2025年04月13日 17时26分45秒