Javascript函数上的call()方法

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call

Function 实例的 call() 方法会以给定的 this 值和逐个提供的参数调用该函数。

语法形式:

call(thisArg)
call(thisArg, arg1)
call(thisArg, arg1, arg2)
call(thisArg, arg1, arg2, /* …, */ argN)

thisArg:在调用 func 时要使用的 this 值。
arg1,arg2,…argN:函数的参数。

返回:使用指定的 this 值和参数调用函数后的结果。

示例:使用 call() 调用函数并指定 this 值

function description() {
    console.log('name = ' + this.name)
}

const obj1 = {
    name: 'tom'
}

const obj2 = {
    name: 'steven'
}

// 打印出tom
description.call(obj1)
// 打印出steven
description.call(obj2)

输出:
在这里插入图片描述

示例:

function description(age) {
    console.log('name = ' + this.name + ' and age = ' + age)
}

const obj1 = {
    name: 'tom'
}

description.call(obj1, 20)

输出:
在这里插入图片描述

示例:如果省略第一个 thisArg 参数,则默认为 undefined,在严格模式下,this 的值不会被替换,因此它保持为 undefined。

globalThis.name = 'tom'

function description() {
    console.log(this)
    console.log('name = ' + this.name)
}

// 抛出TypeError
description.call()

输出:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值