apply call bind的区别以及手写bind和new

1.apply和call直接返回值,apply传参为数组,call传参为依次传

const obj = {
	name:'obj',
}
function fn(a,b,c){
	console.log(this, a,b,c)
}

fn.apply(obj,[1,2,3]) // {name:'obj'} 1 2 3
fn.call(obj,1,2,3) // {name:'obj'} 1 2 3

2. bind返回一个绑定了传入对象的函数

const fn1 = fn.bind(obj,1,2,3)
fn1() // {name:'obj'} 1,2,3

3.手写bind

Function.prototype.newBind = function(context, ...args){
	// 1. 判断是否为函数调用
	if(typeof this !== 'function') throw new TypeError('error')
	context = context|window
	const _this = this
	// 2.返回一个函数
	function BindOf(){
		// 3.调用apply绑定this 并且返回调用结果
		// BindOf是否作为构造函数
		return _this.newApply(this instanceof BindOf? this : context, args)
	}
	BindOf.__proto__ = this.prototype
	return BindOf
}

Function.prototype.newApply = function(context, args){
	// 1. 判断是否为函数调用
	if(typeof this !== 'function') throw new TypeError('error')
	// 2.将函数挂载到需要绑定的对象上
	context = context || window
	context.fn = this 
	// 3.调用函数
	const result = args? context.fn(...args): context.fn()
	// 4.删除挂载上去的函数
	delete context.fn
	// 5.返回结果
	return result
}

fn.newBind(obj,1,2,3)() // {name:'obj'} 1 2 3

4.new的过程以及手写new

function MyNew(fn, ...arr){
	// 1.创建一个新对象
	const obj = {}
	// 2.实例的__proto__ 指向构造函数的prototype属性
	obj.__proto__ = fn.prototype
	// 3.修改this指向实例
	// this.name = name; ==> obj.name = arr[0]
	// this.age = age; ==> obj.age = arr[1]
	// this.sex = 'man' ==> obj.name = 'man'
	fn.apply(obj, arr)
	// 4.返回实例
	return obj
}

function Person(name, age){
	this.name = name;
	this.age = age;
	this.sex = 'man'
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值