介绍
小编给大家分享一下怎么实现es5中的绑定方法,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获、下面让我们一起去了解一下吧!
这样的指向在javascript中一直是个谜一样的存在,但是很多地方又会用到这一点,所以理解和使用这个非常重要,关于此的理解这篇文章不做介绍,因为这篇的目的是改变这样的指向。
改变这样的指向有三种方法,电话,申请,困境。下面先介绍下这三种方法,话不多说了,来一起看看详细的介绍吧
<强>改变这指向强>
<强>调用强>
var a =, { ,名字:“aaa", ,说(类型){ console.log才能(类型、this.name); ,} } a.say (“at");//at aaa var tn =,{名称:“ttt"}; a.say.call (tn,“tt")//tt ttt
可以看到通过电话,说方法中这指的向了tn,传参的方式的列举
<强>适用强>
var a =, { ,名字:“aaa", ,说(类型){ console.log才能(类型、this.name); ,} } a.say (“at"); var tn =,{名称:“ttt"}; a.say.apply (tn, [“tt"])
可以看到通过申请,说方法中这指的向了tn,传参的方式是数组
<强>绑定强>
绑定也能改变这样的指向,不过和调用,应用不同的地方在于,绑定只改变,不会指向函数
var a =, { ,名字:“aaa", ,说(类型){ console.log才能(类型、this.name); ,} } var tn =,{名称:“ttt"}; var b =, a.say.bind (tn); b ();//ttt
绑定改变,也是能够继承原型链的,看下下面的代码
var 用=,{名称:“to",颜色:“red"}; function 动物(){ ,console.log(的名字:$ {this.name}…颜色:$ {this.color} '); } 时间=Animal.prototype.say 函数(){ 说,console.log(. .名字:$ {this.name}…颜色:$ {this.color} '); } var Cat =, Animal.bind (); 猫();//名称:…颜色:红色 var cat =, new 猫();//,名称:未定义…颜色:定义 cat.say();//. .名字说:未定义…颜色:未定义的
因为猫是猫的实例,猫是改变了这样的动物,所以猫也是动物的实例,但这是是指向猫的,所以this.name是未定义的
<强>实现结合强>
Function.prototype.bind =,函数(obj) { ,const args =, Array.prototype.slice.call(参数,1);//保留绑定时的参数=,const that ; ,const bound =,函数(){ const 才能;inArgs =, Array.prototype.slice.call(论点);//执行绑定的函数时的参数 const 才能;newArgs =, args.concat (inArgs);//组装参数 that.apply才能(obj, newArgs);//执行绑定的函数 ,} ,//继承原型——寄生组合式继承 ,function F () {};=,,F.prototype  that.prototype;=,,bound.prototype  new F (); ,return 约束; }
然后执行上面的代码
猫();//名称:…颜色:红色 var cat =, new 猫();//名称:…颜色:红色 cat.say();//. .名字说:未定义…颜色:未定义的
不过第二行和原生的结合还是有点区别的,这里还是记住了之前的绑定的对象,原生的不知道为啥是未定义的
<强>面试题强>
实现es5中的绑定方法,使得下面的代码输出成功
function 动物(名称、颜色){=,this.name 名称;=,this.color 颜色; } 时间=Animal.prototype.say 函数(){ ,return ,“小姐,am a $ {this.color}, $ {this.name} ' } const Cat =, Animal.bind (null,“cat"); const cat =, new 猫(“white"); 如果(cat.say(),===, & # 39;小姐:am a white 猫# 39;,,,,cat instanceof cat ,,, cat instanceof 动物){ ,console.log (“success") }
加上上面的绑定实现,咦? ?没有出现成功? ?为什么?
分析一下代码,绑定的第一个参数是零吗? ?零的时候应该默认为,修改代码如下
Function.prototype.bind =,函数(obj) { ,const args =, Array.prototype.slice.call(参数,1);//保留绑定时的参数=,const that ; ,const bound =,函数(){ const 才能;inArgs =, Array.prototype.slice.call(论点);//执行绑定的函数时的参数 const 才能;newArgs =, args.concat (inArgs);//组装参数 const 才能;bo =, obj | |,; that.apply才能(bo, newArgs);//执行绑定的函数 ,} ,//继承原型——寄生组合式继承 ,function F () {};=,,F.prototype  that.prototype;=,,bound.prototype  new F (); ,return 约束; }怎么实现es5中的绑定方法