美文网首页
js的call函数,apply函数以及bind函数的模拟实现

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

作者: 野蛮生长_ed2e | 来源:发表于2019-07-05 11:19 被阅读0次

一·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) {
  context.fn = this;
  var [obj, ...args] = [... arguments];
  context.fn(...args);
  delete context.fn;
}
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());

相关文章

网友评论

      本文标题:js的call函数,apply函数以及bind函数的模拟实现

      本文链接:https://www.haomeiwen.com/subject/aayshctx.html