当前位置: 移动技术网 > IT编程>开发语言>JavaScript > javascript中call,apply,bind函数用法示例

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

2019年04月04日  | 移动技术网IT编程  | 我要评论

本文实例讲述了javascript中call,apply,bind函数用法。分享给大家供大家参考,具体如下:

一.call函数

a.call(b);

简单的理解:把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数学运算用法总结

希望本文所述对大家javascript程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网