call方法的使用 js 230220

江南北

关注

阅读 101

2023-02-20

传统调用方法

用法:

方法名()


示例:

function fn() {
console.log("fn方法被调用")
console.log(this)
}

// 关注方法的调用
// 方法名()
fn()


call方法调用


用法:

构造方法名.call()


示例:


function fn() {
console.log("fn方法用call调用")
console.log(this)
}
// 对象.方法名()
// 方法体对象.call()
fn.call()


call可改变this

如果call方法调用时传入了一个参数

这个参数会替代原方法

function fn() {
console.log("fn方法用call调用")
console.log(this)
}

var xm = {"name": "小明", "age": 16}

// 使用call改变this
fn.call(xm)


call传参的情况


call的参数2会传给方法的形参1

call的参数3会传给方法的形参2


function fn(name,age) {
console.log("fn方法用call调用")
console.log(name)
console.log(this)
}

var xm = {"name": "小明", "age": 16}

// 使用call改变this
fn.call(xm,"tom",16)


精彩评论(0)

0 0 举报