JavaScript中的call()函数如何使用

其他教程   发布日期:2023年10月18日   浏览次数:442

本篇内容介绍了“JavaScript中的call()函数如何使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

this指向

1.指向window:

  1. var name = '小红'
  2. function foo () {
  3. console.log(this.name) //小红
  4. }
  5. foo() //直接调用方法指向的就是window

2.指向直接调用者:

  1. var name = '小红'
  2. var object = {
  3. name: '李白',
  4. function foo () {
  5. console.log(this.name) //李白
  6. }
  7. }
  8. object.foo() //object直接调用foo(),this指向object

3.指向new 实例:

  1. var name = '小红'
  2. function foo () {
  3. this.name = '小白'
  4. console.log(this.name) //小白
  5. }
  6. var fn = new foo() //this指向foo()的实例fn

this指向问题还是比较好理解的

总结下来就是一句话:

  1. 谁调用的函数,this就是谁

下面说一下call()函数,call()跟我们正常思维模式不太一样,脑回路回转下

Call()指向

简单一句话: B.call(A) <==>A调用B函数,可以解释为B的this指向A。

代码示例:

  1. function _add() {
  2. console.log(this.test);
  3. }
  4. function _sub() {
  5. this.test = 222;
  6. console.log(this.test);
  7. }
  8. _add.call(_sub); //输出undefine。这时,_add的this指向_sub,
  9. _sub里的this指向是window,所以_sub本身没有test这个属性
  10. _add.call(new _sub())//输出222。这时,_add的this指向_sub,
  11. _sub里的this指向是_sub实例,可以获取到_subtest属性,所以输出222
  12. /******************************************************/
  13. function _add() {
  14. this.test = 444
  15. console.log(this.test);
  16. }
  17. function _sub() {
  18. this.test = 222;
  19. console.log(this.test);
  20. }
  21. _add.call(_sub); //输出444。这时,_sub里的this指向是window,

所以_sub里没有test这个属性,但是_add的this指向_sub,并为_sub创建了test属性,所以可以获取到test的值为444

如果你觉得上面说的都不是很好理解,还有方便记忆的方法

猫吃鱼,狗吃肉,奥特曼打小怪兽。
有天狗想吃鱼了
猫.吃鱼.call(狗,鱼) // 狗调用的吃鱼的函数,所以this是狗
狗就吃到鱼了
猫成精了,想打怪兽
奥特曼.打小怪兽.call(猫,小怪兽) // 猫调用了打怪兽的函数,所以this是猫

再通俗一点就是

马云会赚钱
我使用call()函数借用了马云的赚钱函数,
所以我也会赚钱了
马云.赚钱.call(我)
此时this指向我
因为是我调用的赚钱函数

以上就是JavaScript中的call()函数如何使用的详细内容,更多关于JavaScript中的call()函数如何使用的资料请关注九品源码其它相关文章!