js的call函数,apply函数以及bind函数的模拟实现

一·call函数的作用

var foo = {val: 1}
function a() {
console.log(this.val);
}
a.call(foo); // 1

接下来我们开始封装一个call函数

var foo = {
 val: 1,
 bar: function(){console.log(this.val);}
}
foo.bar(); // 1 

只要我们将其封装成以上这种格式就可以了
call方法可以理解为将call方法里面的参数1变量的参数二参数三‘拷’过来

如果参数不确定
// 最终版
Function.prototype.call4 = function (context) {
  // 首先判断是不是函数调用该方法,如果不是,则抛出异常
    if (typeof this !== "function") throw new TypeError('Error');

    // 为**null或undefined**时,要把this指向window
    var context = context || window;
    // 将函数设置为obj的属性
    context.fn = this;

    // 类数组解构参数
    var args = [...arguments].slice(1);

    // 执行函数
    var result = context.fn(...args);

    // 删除函数
    delete context.fn;
    return result;
}
var a = {val: 11};
function b(name, age) { console.log(name, age, this.val); }
b.call4(a, 'wangxiaoer', '12');

二、apply函数(同理)

Function.prototype.apply1 = function (context) {
var context = context || window
context.fn = this

var result
// 需要判断是否存储第二个参数
// 如果存在,就将第二个参数展开
if (arguments[1]) {
  result = context.fn(...arguments[1])
} else {
  result = context.fn()
}

delete context.fn
return result
}
var a = {val: 11}; 
function b(name, age) { console.log(name, age, this.val); }
b.apply1(a, ['wangxiaoer', '12']);
agruments数据结构

三.bind函数

var module = {
  x: 42,
  getX: function() {
    return this.x;
  }
}

var unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined

var boundGetX = unboundGetX.bind(module);
console.log(boundGetX()); // 42


Function.prototype.myBind = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  var _this = this
  var args = [...arguments].slice(1)
  // 返回一个函数
  return function F() {
    // 因为返回了一个函数,我们可以 new F(),所以需要判断
    if (this instanceof F) {
      return new _this(...args, ...arguments)
    }
    return _this.apply(context, args.concat(...arguments))
  }
  /*
这个时候的arguments是指bind返回的函数传入的参数也就是bindFoo调用是传入的18
var foo = {
     value: 1
};

function bar(name, age) {
   console.log(this.value);
    console.log(name);
    console.log(age);

}

var bindFoo = bar.bind(foo, 'daisy');
bindFoo('18');
// 1
// daisy
// 18
}*/

var module = {
  x: 42,
  getX: function() {
    return this.x;
  }
}

var boundGetX = module.getX.myBind(module);
console.log(boundGetX());
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 单例模式 适用场景:可能会在场景中使用到对象,但只有一个实例,加载时并不主动创建,需要时才创建 最常见的单例模式,...
    Obeing阅读 2,112评论 1 10
  • 一、JavaScript基础知识回顾 1.1 JavaScript 1.1.1 javascript是什么? Ja...
    福尔摩鸡阅读 1,359评论 0 7
  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 9,356评论 0 3
  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 7,915评论 2 17
  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 2,060评论 0 2