javascript实现原生方法

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值