call、apply和bind的⽤法及区别
⼀、call和apply
1、call和apply都是ype的⽅法,每⼀个⽅法的对象实例newfunction()都会有这两个属性;
2、这两个属性都是针对⽅法的属性针对⽅法使⽤;
3、call和apply使⽤⽅法相同;
4、call和apply的参数不同;
(1)(this,param1,param2,param3);//可以传多个参数
(2)(this,paramArray);//只能传两个参数,第⼆个⼀般为数组
⼆、bind
call和apply会改变this指向,然后执⾏函数;
bind会改变this指向后,返回⼀个绑定新this的函数;
三、demo
varname="aven";
varage=18;
varobj={
name:"ake",
age:,
test:function(){
("name:",,"age:",);
}
};
();
//name:akeage:undefined
//因为()只会调⽤本⾝属性,本⾝没有age属性,但是有name属性
()
//name:avenage:18
//call参数为null或undefined时默认指向window,
//this含有属性name:"aven",age:18,所以输出结果变化
varname="testName";
varage=18;
varobj={
name:"ake",
age:,
test:function(gender,home){
("name:",,"age:",,"gender:",gender,"home:",home);
}
};
varperson={
name:"aven",
age:18
}
(person,"female","China")//name:avenage:18gender:femalehome:China
(person,["female","China"])//name:avenage:18gender:femalehome:China
(person,"female","China")()//name:avenage:18gender:femalehome:China
(person,["female","China"])()//name:avenage:18gender:["female","China"]home:undefined
(this,"female","China")()//name:testNameage:18gender:femalehome:China
四、实现call⽅法
=function(){
var_this=arguments[0]
varparams=[...arguments].slice(1)
varisStrict=(function(){returnthis===undefined})
if(!isStrict){
//如果是其他原始值,需要通过构造函数包装成对象
vartype=typeof_this;
if(type==='number'){
_this=newNumber(_this)
}elif(type==='string'){
_this=newString(_this)
}elif(type==='boolean'){
_this=newBoolean(_this)
}
}
varinvokeFun=this;
if(_this===null||_this===undefined){
returninvokeFunc(...params)
}
varuniquePropName=Symbol(_this)
_this[uniquePropName]=invokeFun
return_this[uniquePropName](...params)
}
五、实现⼀个apply,跟call相似,把参数列表改为参数数组
y=function(_this,params){
varisStrict=(function(){returnthis===undefined}())
if(!isStrict){
//如果是其他原始值,需要通过构造函数包装成对象
vartype=typeof_this;
if(type==='number'){
_this=newNumber(_this)
}elif(type==='string'){
_this=newString(_this)
}elif(type==='boolean'){
_this=newBoolean(_this)
}
}
varinvokeFun=this
varinvokeParams=y(params)?params:[]
if(_this===null||_this===undefined){
returninvokeFun(...invokeParams)
}
uniquePropName=Symbol(_this)
_this[uniquePropName]=invokeFun
return_this[uniquePropName](...invokeParams)
}
六、实现bind,区别在于
=function(){
varboundTargetFunc=this;
if(typeofboundTargetFunc!=='function'){
thrownewError('绑定的⽬标必须是函数')
}
varboundThis=arguments[0];
varboundParams=[].(arguments,1);
functionfBound(){
varrestParams=[].(arguments);
varallParams=(restParams)
(thisinstanceoffBound?this:boundThis,allParams)
}
ype=(ype||ype)
returnfBound
}
本文发布于:2022-11-26 08:18:01,感谢您对本站的认可!
本文链接:http://www.wtabcd.cn/fanwen/fan/90/23918.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |