js中bind、call、apply、reduce、Promise.all、new等函数的实现

1、bind
Function.prototype.myBind = function(context, ...arg0) {
  let that = this;
  let FNOP = function() {};
  let Bound = function(...args1) {//保证柯里化
    return that.apply(
      this instanceof Bound ? this : context,//判断使用new的情况
      arg0.concat(args1)
    );
  };
  //维护原型关系
  if (this.prototype) FNOP.prototype = this.prototype;
  Bound.prototype = new FNOP();
  return Bound;
};
2、call
Function.prototype.myCall=function (context,...args){
    context.fun=this;//改变函数的this;
    return context.fun(...args);
}
let obj={age:10};
function getAge(age){
    console.log(this.age);
}
getAge(20);
getAge.call(obj,20);
getAge.myCall(obj,20);

 

3、apply
Function.prototype.myApply=function (context,args){
    context.fun=this;//改变函数的this;
    return context.fun(...args);
}
let obj={age:10};
function getAge(age){
    console.log(this.age,age);
}
getAge(20);
getAge.apply(obj,[20]);
getAge.myApply(obj,[20]);
4.map
Array.prototype.myMap1 = function(fn) {
  let res = [];
  for (let i = 0; i < this.length; i++) {
    res.push(fn.call(null, this[i], i));
  }
  return res;
};
//reduce实现map
Array.prototype.myMap2 = function(fn) {
  return this.reduce((prev, val) => {
    prev.push(fn.call(null, val));
    return prev;
  }, []);
};

 

5、reduce
Array.prototype.myReduce = function (fn, init) {
    let i, prev;
    if (arguments.length >= 2) {
        prev = init;
        i = 0;
    } else {
        prev = this[0];
        i = 1;
    }
    for (; i < this.length; i++) {
        prev = fn.call(null, prev, this[i], i);
    }
    return prev;
};
var arr = [1, 2, 3];
console.log(arr.reduce((prev, val) => prev + val));
console.log(arr.myReduce((prev, val) => prev + val));
console.log(arr.myReduce((prev, val) => { prev.push(val * 2); return prev; }, []));

 

6、promise.all的实现
Promise.myAll = function(promises) {//两点:传入的是一个数组,返回的是Promise
  if (!Array.isArray(promises)) {
    throw new TypeError("params is not an array!");
  }
  return new Promise(function(resolve, reject) {
    let res = [];
    for (let i = 0; i < promises.length; i++) {
      Promise.resolve(promises[i])
        .then(result => {
          res.push(result);
          if (res.length == promises.length) {
            resolve(res);
          }
        })
        .catch(error => {
          reject(error);
        });
    }
  });
};

const p1 = new Promise((resolve, reject) => {
  throw new Error("报错了");
});

const p2 = new Promise((resolve, reject) => {
  resolve("hello");
});

Promise.all([p1, p2])
  .then(result => console.log(result))
  .catch(e => console.log(e));
Promise.myAll([p1, p2])
  .then(result => console.log(result))
  .catch(e => console.log(e));

// const p3 = new Promise((resolve, reject) => {
//   throw new Error("报错了");
// })
//   .then(result => result)
//   .catch(e => e);

// const p4 = new Promise((resolve, reject) => {
//   resolve("hello");
// })
//   .then(result => result)
//   .catch(e => e);

// Promise.all([p3, p4])
//   .then(result => console.log(result))
//   .catch(e => console.log(e));
// Promise.myAll([p3, p4])
//   .then(result => console.log(result))
//   .catch(e => console.log(e));
7、new
function _new(constructor, ...args){
    if(typeof constructor !== 'function'){
        throw new Error('constructor is not a function');
    }
    let obj=Object.create(constructor.prototype);//用函数原型创建对象
    let res=constructor.apppy(obj,args);
    if(res!==null&&typeof res=='object'){//如果有返回值,且返回值是对象,则返回对象
        return res;
    }
    return obj;//否则返回obj
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值