JavaScript 函数 Call的使用
JavaScript 函数 Call的使用
call的语法
function.call(obj,...args)
Call的作用是什么呢?通俗来说:
我手机没电了,借朋友的手机发个短信,注意是借用,当你用完以后你“朋友手机的短信功能”对你来说就失效了,除非你再次借用。
这里就有两个对象我、朋友,那短信功能就是所说的方法
先来创建“我”这个对象和方法(因为手机没有电了,所以没有发短信的方法,注释掉就好):
var me={name:'我',/*sendMsg:function(target,content){console.log("【"+this.name+"】给【"+target+"】发送了短信:"+content);}*/
}
再来看朋友A对象
var friendA={name:'朋友A',sendMsg:function(target,content){console.log("【"+this.name+"】给【"+target+"】发送了短信:"+content);}
}
我们来调用一下方法发送给朋友B短信
var me={name:'我',/*sendMsg:function(target,content){console.log("【"+this.name+"】给【"+target+"】发送了短信:"+content);}*/
}var friendA={name:'朋友A',sendMsg:function(target,content){console.log("【"+this.name+"】给【"+target+"】发送了短信:"+content);}
}friendA.sendMsg('朋友B','你好啊老朋友!');
me.sendMsg('朋友B','你好啊老朋友!');
得到的结果是:
【朋友A】给【朋友B】发送了短信:你好啊老朋友!
Uncaught TypeError: me.sendMsg is not a function
可以看到朋友A正常的给朋友B发送了短信,然后我就发送不成功,为什么,因为“我”这个对象没有发送短信的方法,手机没电了,那怎么办,用call函数来借一下朋友A的手机:
这样用:friendA.sendMsg.call(me,'朋友B','你好啊老朋友!');
friendA.sendMsg 是要借用的方法
me 是谁要借用
'朋友B','你好啊老朋友!' 传入的实参
完整代码如下:
var me={name:'我',/*sendMsg:function(target,content){console.log("【"+this.name+"】给【"+target+"】发送了短信:"+content);}*/
}var friendA={name:'朋友A',sendMsg:function(target,content){console.log("【"+this.name+"】给【"+target+"】发送了短信:"+content);}
}friendA.sendMsg('朋友B','你好啊老朋友!');
//me.sendMsg('朋友B','你好啊老朋友!');friendA.sendMsg.call(me,'朋友B','你好啊老朋友!');
输出结果:
【朋友A】给【朋友B】发送了短信:你好啊老朋友!
【我】给【朋友B】发送了短信:你好啊老朋友!
朋友A和我都通过朋友A的手机向朋友B问好了,效果达到了,手机要还给朋友A,因为我的手机还是没有电,所以我还是没有发送短信这个功能!