关于JS中一些重要的api实现, 巩固你的原生JS功底(一)

未结 0 3141
VIP1 2019年09月20日
悬赏:20积分

一、用ES5实现数组的map方法
核心要点:

1.回调函数的参数有哪些,返回值如何处理。

2.不修改原来的数组。


Array.prototype.MyMap = function(fn, context){
var arr = Array.prototype.slice.call(this);//由于是ES5所以就不用...展开符了
var mappedArr = [];
for (var i = 0; i < arr.length; i++ ){
mappedArr.push(fn.call(context, arr[i], i, this));
}
return mappedArr;
}

二、用ES5实现数组的reduce方法
核心要点:

1、初始值不传怎么处理

2、回调函数的参数有哪些,返回值如何处理。

Array.prototype.myReduce = function(fn, initialValue) {
var arr = Array.prototype.slice.call(this);
var res, startIndex;
res = initialValue ? initialValue : arr[0];
startIndex = initialValue ? 0 : 1;
for(var i = startIndex; i < arr.length; i++) {
res = fn.call(null, res, arr[i], i, this);
}
return res;
}


三、实现call/apply
思路: 利用this的上下文特性。

//实现apply只要把下一行中的...args换成args即可
Function.prototype.myCall = function(context = window, ...args) {
let func = this;
let fn = Symbol("fn");
context[fn] = func;

let res = context[fn](...args);//重点代码,利用this指向,相当于context.caller(...args)

delete context[fn];
return res;
}


四、实现Object.create方法(常用)

function create(proto) {
function F() {};
F.prototype = proto;
F.prototype.constructor = F;

return new F();
}

五、实现bind方法
核心要点:

1.对于普通函数,绑定this指向

2.对于构造函数,要保证原函数的原型对象上的属性不能丢失

Function.prototype.bind = function(context, ...args) {
let self = this;//谨记this表示调用bind的函数
let fBound = function() {
//this instanceof fBound为true表示构造函数的情况。如new func.bind(obj)
return self.apply(this instanceof fBound ? this : context || window, args.concat(Array.prototype.slice.call(arguments)));
}
fBound.prototype = Object.create(this.prototype);//保证原函数的原型对象上的属性不丢失
return fBound;
}



转自 掘金 神三元
链接:https://juejin.im/post/5d635566e51d4561e224a360

回帖
  • 还没有人回复
本周热议
没有相关数据
layui

微信扫码关注 网盟开源 公众号