javascript中call,apply,bind函数用法示例

简单的理解:把a对象的方法应用到b对象上(a里如果有this,会指向b)

call()的用法:用在函数上面

var Dog=function(){ this.name="汪星人"; this.shout=function(){ alert(this.name); } }; var Cat=function(){ this.name="喵星人"; this.shout=function(){ alert(this.name); } }; var dog=new Dog(); var cat=new Cat(); dog.shout(); cat.shout();

如果猫函数中没有shout方法,要达到一样的效果

var Dog=function(){ this.name="汪星人"; this.shout=function(){ alert(this.name); } }; var Cat=function(){ this.name="喵星人"; }; var dog=new Dog(); var cat=new Cat(); dog.shout(); dog.shout.call(cat); cat.shout();

call的作用:函数可以复用

二、apply函数

var xh= { name:"小红", job:"前端工程师" }; var xm= { name:"小明", job:"js工程师" }; var xw= { name:"小王", job:"html5工程师" }; function myjob(gender,age,company) { alert(this.name+","+gender+",今年"+age+"岁,在"+company+"担任"+this.job); } myjob.call(xh,"女",24,"腾讯"); myjob.call(xm,"男",22,"新浪"); myjob.call(xw,"男",28,"网易");

call函数和apply函数功能一样,区别是第二个参数形式不一样,call传递多个参数,任意形式(传入参数和函数所接受参数一一对应),apply第二个参数必须是数组形式,如a.call(b,2,3); ==>  a.apply(b,[2,3]);

var xh= { name:"小红", job:"前端工程师" }; var xm= { name:"小明", job:"js工程师" }; var xw= { name:"小王", job:"html5工程师" }; function myjob(gender,age,company) { alert(this.name+","+gender+",今年"+age+"岁,在"+company+"担任"+this.job); } myjob.apply(xh,["女",24,"腾讯"]); myjob.apply(xm,["男",22,"新浪"]); myjob.apply(xw,["男",28,"网易"]);

三、bind函数

call,apply和bind都可以“绑架”this,逼迫其指向其他对象

使用上和call,apply的区别,如

xw.say.call(xh); //对函数直接调用 xw.say.apply(xh); //对函数直接调用 xw.say.bind(xh)(); //返回的仍然是一个函数,因此后面需要()来调用

传参时可以像call那样

xw.say.bind(xh,"中央大学","一年级")();

由于bind返回的仍然是一个函数,所以也可以在调用时再进行传参

xw.say.bind(xh)("中央大学","一年级");

更多关于JavaScript相关内容可查看本站专题:《javascript面向对象入门教程》、《JavaScript中json操作技巧总结》、《JavaScript切换特效与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwfwxs.html