重写 js 里的 apply、call、bind 和 new 方法

12 篇文章 0 订阅

用了这么久的这些方法以后,特别想深究其实现原理,所以在参考了很多资料以后,试着自己再手写一遍,记录在此,方便以后查找、回忆,或者帮助别人理解这些方法。

1、apply方法:

Function.prototype.myApply=function(){
	let f = this;
	if(typeof f !== 'function'){
		throw new TypeError('error');
	}
	let arg = [...arguments].slice(1).shift();//1、类数组对象转化成数组;
											//2、slice是取出所有的参数,此时是一个二维数组
											//所以还需要用shift()来取出参数数组。或者这么写: [...arguments].slice(1)[0]
	let res = f(...arg);//利用...实现函数多参数传递
	return res;
}
//试验一下
let max = Math.max.myApply(null,[1,2,3,4,5,6])//Math.max()方法,要求传入的是一个个的参数,而不能是数组
console.log(max)

2、call 方法

Function.prototype.myCall = function(){
	let f = this;
	if(typeof f !== 'function'){
		throw new TypeError('error');
	}
	let arg = [...[...arguments].slice(1)];
	let res = f(...arg);
	return res;
}
let max = Math.max.myCall(null,1,2,3,4,5,6);
console.log(max);

小结:call 和 apply 方法其实都是:括号内的对象可以调用括号外的方法,只是传参不一样。apply必须是一个数组;而call是一个个零散的参数

3、bind 方法

bind 方法的主要作用:和 call 以及 apply 一样,也是将函数绑定到某个对象。但是 bind() 会创建一个新函数,函数体内的this对象的值会被绑定为 bind() 中的第一个参数,例如:func.bind(obj),实际上可以理解为 obj.func(),这时f函数体内的this自然指向的是 obj;

Function.prototype.my_bind = function(){
    //确保调用bind方法的一定要是一个函数
    if(typeof this !== "function"){
        throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }
    let context = [...arguments].shift();
    let args = [...arguments].slice(1);
    let self = this;
    let F = function(){};
    F.prototype = this.prototype;
    let bound = function(){
        var innerArgs = [...arguments].slice();
        var finalArgs = [...args,...innerArgs];
        return self.apply(this instanceof F ? this : context || this, finalArgs);
    }
    bound.prototype = new F(); //为什么要先新建一个空对象,然后让bound函数的原型指向它的实例呢?
    						//这是尊重原型链的写法,比直接写bound.prototype = this.prototype要安全。
    						//不然他们指向同一个地址,修改bound这个子对象里的方法属性,就直接影响到父对象了。
    return bound;
}

		 
	//测试
	function a(m, n, o){
	    return this.name + ' ' + m + ' ' + n + ' ' + o;
	}
	 
	var b = {name : 'kong'};
	 
	var ss = a.my_bind(b, 7, 8)(9); 
	
	console.log( ss)  //kong 7 8 9

4、new 方法

new方法其实干了如下几件事:
(1)、创建一个新的空对象;
(2)、链接到原型
(3)、绑定this指向,执行构造函数
(4)、确保返回的是对象

function myNew(){
	let o = {};
	let context = [...arguments].shift();
	let args = [...arguments].slice(1);
	o.__proto__ = context.prototype;
	context.apply(o,args);
	return o;
}

//测试
function sayHi(name){
	this.name = name;
	this.say = function(){
		console.log('hello '+this.name)
	}
}

let Jack = myNew(sayHi, 'jack');
Jack.say();// hello jack
let Tom = myNew(sayHi, 'tom');
Tom.say();// hello tom
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值