您的位置:首页 > 移动开发

ES5 function 扩展:call()、apply()、bind()详解

2019-07-17 10:14 1281 查看
Function.prototype.call()
  • Function.prototype.call(thisArg[, arg1[, arg2[, ...]]])
    提供新的 this 值给当前调用的函数或方法。

    thisArg
    在 fun 函数运行时指定的
    this
    值。需要注意的是,指定的
    this
    值并不一定是该函数执行时真正的
    this
    值,如果这个函数在
    非严格模式
    下运行,则指定为
    null
    undefined
    this
    值会自动指向全局对象。
  • arg1, arg2, ...
    指定的参数列表。

示例:

var obj = {username: '小乔', age: 19}
function fun(data) {
console.log(this, data)
}
// 执行结果:Window{...} "test"
fun('test') // 此时 this 指向的是 window
// 执行结果:{username: "小乔", age: 19} "www"
fun.call(obj, 'www') // 此时 this 的指向已改变
Function.prototype.apply()
  • Function.prototype.apply(thisArg, [argsArray])
    为当前被调用的函数指定一个 this 对象。

    thisArg
    在 fun 函数运行时指定的
    this
    值。。。
  • argsArray
    一个数组或者类数组对象,其中的数组元素将作为单独的参数传给 fun 函数。
  • apply
    call()
    非常相似,不同之处在于提供参数的方式。

示例:

var obj = {username: '小乔', age: 19}
function fun(data) {
console.log(this, data)
}
// 执行结果:Window{...} "test"
fun('test') // 此时 this 指向的是 window
// 执行结果:{username: "小乔", age: 19} "www"
fun.apply(obj, ['www']) // 此时 this 的指向已改变
Function.prototype.bind()
  • Function.prototype.bind(thisArg[, arg1[, arg2[, ...]]])
    创建一个新的函数,在
    bind()
    被调用时,这个新函数的
    this
    被bind的第一个参数指定,其余的参数将作为新函数的参数供调用时使用。

    thisArg
    调用绑定函数时作为
    this
    参数传递给目标函数的值。
  • arg1, arg2...
    当目标函数被调用时,预先添加到绑定函数的参数列表中的参数。
  • 返回值:返回一个原函数的拷贝,并拥有指定的this值和初始参数。

示例:

var obj = {username: '小乔', age: 19}
function fun(data) {
console.log(this, data)
}
// 执行结果:Window{...} "test"
fun('test') // 此时 this 指向的是 window
// 执行结果:{username: "小乔", age: 19} ["www"]
fun.bind(obj, ['www'])() // 此时 this 的指向已改变

注:

  • 与上面的两个方法不同,
    bind()
    绑定完 this 不会立即调用当前函数,而是将函数返回。
  • 通常用来指定回调函数的
    this
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: