当前位置: 首页 > Web前端 > HTML

new、apply、call、bind实现

时间:2023-03-28 12:12:43 HTML

new关键字new关键字的主要作用是执行一个构造函数,返回一个实例对象。在new的过程中,根据构造函数的情况,判断是否可以接受传入的参数。functionPerson(){this.name='Jack';}varp=newPerson();console.log(p.name)//这段代码Jack做了四件事来创建一个新对象;范围分配给新对象(this指向新对象);执行构造函数中的代码(向这个新对象添加属性);返回新对象。functionPerson(){this.name='汤姆';返回{age:18}}varp=newPerson();console.log(p)//{age:18}console.log(p.name)//undefinedconsole.log(p.age)//18时构造函数最后返回的是一个对象,与this,新命令会直接返回这个新对象,而不是新执行步骤生成的this对象。函数Person(){this.name='Jack';返回'??tom';}varp=newPerson();console.log(p)//{name:'Jack'}console.log(p.name)//Jack在构造函数中返回的不是对象时,仍然会生成一个新的对象(用最新的this绑定)根据new关键字的执行逻辑,最终返回。因此,new关键字执行后,总是返回一个对象,要么是实例对象,要么是return语句指定的对象。new的实现new被访问后做的几件事允许实例访问私有属性允许实例访问构造函数原型(constructor.prototype)所在原型链上的属性构造函数返回引用数据类型函数_new(contor,...args){if(typeofcontor!=="function"){throw"controlmustbeafunction"}//构造一个obj实例对象letobj=newObject()//__proto__可以理解为“构造函数”的原型,即__proto__===constructor.prototypeobj.__proto__=Object.create(contor.prototype)letres=contor.apply(obj,[...args])letisObj=typeofres==="对象"&&res!==null;让isFunction=typeofres===“函数”返回isObj||是功能?res:obj}apply,call,bind这三个函数比较常用,把this改成指向func.call(thisArg,param1,param2,...)func.apply(thisArg,[param1,param2,...])func.bind(thisArg,param1,param2,...)调用,应用实现Function.prototype.call=function(context,...args){varcontext=context||窗户;context.fn=这个;//立即执行letresult=eval("context.fn(...args)")deletecontext.fnreturnresult;}功能。prototype.apply=function(context,args){varcontext=context||}窗户;context.fn=这个;//立即执行letresult=eval("context.fn(...args)")deletecontext.fnreturnresult;}Function.prototype.bind=function(context,...args){if(typeof!=="function"){thrownewError("thismustbeafunction")}letself=this;letfbound=function(){self.apply(thisinstanceofself?this:context,args.concat(Array.prototype.slice.call(arguments)))}if(this.prototype){//返回进程内原型链对象上的属性不能丢失。把this.prototype上的属性挂到fbound的原型上fbound.prototype=Object.create(this.prototype)}//实现bind的核心是返回一个函数returnfbound}