js函数 :Call Apply 使用方法 和 区别

本文通过示例详细介绍了Vue中Function.prototype.call()和.apply()的区别,主要在于参数传递方式的不同。call方法接收参数为逗号分隔的形式,而apply则是数组形式。文中展示了如何在组件中使用这两种方法来改变函数调用的上下文,并演示了它们在计算属性中的应用,帮助读者更好地理解和运用这两个方法。
摘要由CSDN通过智能技术生成

Call Apply 使用方法 和 区别

一、区别:

区别:在于传参时:Apply是数组 [xxx,xxx]的形式;Call是xxx,xxx的形式 ,下面例子可看

w3school中的参考文档

<template>
  <div>
    <p>Call 参数:{{ fullName3 }}</p>
    <p>Apply 参数:{{ fullName4 }}</p>
  </div>
</template>

<script>
export default {
  name: "XuexiKuangjiaCallApply",

  data() {
    return {
      person: {
        firstName: "AAA",
        lastName: "BBB",
        fullName: function () {
          return this.firstName + this.lastName;
        },
      },
      name: {
        firstName: "111",
        lastName: "222",
      },
      person2: {
        fullName: function () {
          return this.firstName + this.lastName;
        },
        fullName3: function (x, y) {
          return this.firstName + this.lastName + x + y;
        },
      },
    };
  },
  computed: {
    fullName2: function () {
      return this.person2.fullName.call(this.name);//结果111222
    },
    fullName3: function () {
      return this.person2.fullName3.call(this.name, 5, 6);//结果 11122256
    },
    fullName4: function () {
      return this.person2.fullName3.apply(this.name, [8, 8]);//结果 11122288
    },
  },


};
</script>

<style lang="scss" scoped>
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值