Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

手写实现call,apply,bind #25

Open
heyushuo opened this issue Dec 27, 2019 · 0 comments
Open

手写实现call,apply,bind #25

heyushuo opened this issue Dec 27, 2019 · 0 comments

Comments

@heyushuo
Copy link
Owner

前言

手写实现 call、apply 和 bind,首先我们需要了解三个方法的区别,我以前写过一篇文章详细介绍了三者的区别,读完再读本文会更容易理解

手写实现 call 方法

实现思路就是这段话所描述的,引用你不知道的 JavaScript 中的一段话当函数引用有上下文对象时,隐式绑定规则会把函数调用中的 this 绑定到这个上下文对象。

Function.prototype.myCall = function(context) {
  context = context || window; // 如果context传的是null或者undefined则默认context是window
  context.fn = this; //这里this指的是调用myCall的函数;
  var args = [...arguments].slice(1); //把arguments伪数组变成数组,在截取除了第一个之后的参数
  var result = context.fn(...args); //立即执行函数,执行函数的时候把参数传入
  delete context.fn; //把函数删除掉,为了还原外部obj对象,把添加到他上边的属性在删除掉
  return result;
};

function ceshi() {
  console.log(this.name); //kebi
  console.log([...arguments]); //['25']
}
var obj = {
  name: 'kebi'
};
ceshi.myCall(obj, '25');

手写实现 apply 方法

apply 第二个参数是数组

Function.prototype.myApply = function(context) {
  context = context || window; // 如果context传的是null或者undefined则默认context是window
  context.fn = this;
  var args = arguments[1]; // 取传参数的第二个参数
  var result;
  if (args) {
    result = context.fn(...args);
  } else {
    result = context.fn();
  }
  delete context.fn; //把函数删除掉,为了还原外部obj对象,把添加到他上边的属性在删除掉
  return result;
};
function ceshi() {
  console.log(this.name); //kebi
  console.log([...arguments]); //[1, 2, 3]
}
var obj = {
  name: 'kebi'
};
ceshi.myApply(obj, [1, 2, 3]);

手写实现 bind 方法

bind 方法不会立即执行函数,需要我们返回一个函数

Function.prototype.myBind = function(context) {
  var _this = this;

  var args = [...arguments].slice(1); //把arguments伪数组变成数组,在截取除了第一个之后的参数或者 Array.prototype.slice.call(arguments, 1);
  return function() {
    //获取执行bind绑定函数返回的函数的参数
    var bingArgs = [...arguments];
    return _this.apply(context, args.concat(bingArgs));
  };
};

function bindFn() {
  console.log('姓名:' + this.name + '年龄:' + this.age); //姓名:kebi 年龄:3
  console.log([...arguments]); // [[1,2,3],测试]
}
var bindObj = {
  name: 'kebi',
  age: 35
};
var fun = bindFn.myBind(bindObj, [1, 2, 3], '测试');
fun(); //执行函数

bind 实现到这里还是有点问题的,当把 bind 返回的函数当做构造函数,new 的时候 this 的指向就变了,需要了解详细的可以查看下边连接

JavaScript 深入之 bind 的模拟实现

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant