1、js实现Number对象的toFixed方法
Number.prototype.toFixed = function (s) {
changenum = (
parseInt(this * Math.pow(10, s) + 0.5) / Math.pow(10, s)
).toString();
index = changenum.indexOf('.');
if (index < 0 && s > 0) {
changenum = changenum + '.';
for (i = 0; i < s; i++) {
changenum = changenum + '0';
}
} else {
index = changenum.length - index;
for (i = 0; i < s - index + 1; i++) {
changenum = changenum + '0';
}
}
return changenum;
};
2、实现new
function _new (constructor, ...args){
// 创建一个空对象
const resultObj = {};
// 将构造函数的原型复制给对象的原型;
resultObj.__proto__ = constructor.prototype;
// 将创建的对象作为this的上下文
let result = constructor.call(resultObj, ...args);
// 如果该函数没有返回对象(result不是对象),则返回resultObj;
return typeof result === 'object' ? result : resultObj;
}
3、call方法实现
Function.prototype.mycall = function(){
// 获取第一个参数
const target = argunments[0] || window;
// 获取传递参数
const args = Array.from(arguments).slice(1);
// 将当前对象赋值给target
target.fn = this;
// 执行改方法
target.fn(...args);
// 删除fn
delete target.fn;
}
4、apply方法实现
Function.prototype.myApply = function(){
// 获取第一个参数
const target = arguments[0] || window;
const args = arguments[1];
target.fn = this;
// 执行fn;
target.fn(...args);
// 删除fn
delete target.fn;
}
5、bind方法实现
Function.prototype.myBind = function(){
const target = arguments[0] || window;
const args = Array.from(arguments).slice(1);
const fn = this;
// 返回一个函数
return function(){
fn.call(target, ...args, ...arguments);
}
}
6、reduce实现
Array.prototype.myReduce = function(fn, initValue){
if(initValue == undefined && !this.length){
throw new Error(Reduce of empty array with no initial value);
}
let result = initValue ? initValue : this[0];
for(let i = initValue ? 1 : 0; i < this.length; i++){
fn(result, this[i], i, this);
}
return result;
}