JavaScript学习笔记(十) call、apply、bind

call、apply、bind 都是定义在函数原型上的,也就是说每个函数都能调用这些方法

那么它们都有什么作用呢?它们之间存在什么异同呢?下面让我们一起来探讨一下

1、call 和 apply

call 的作用与 apply 完全一样,用于改变函数的执行环境,也就是说改变函数内部 this 的指向

通过这些方法,可以让一个对象借用另一个对象的方法,可以实现继承,两者的区别仅仅在于传入的参数

  • 第一个传入的参数都是上下文执行环境,表示函数运行时 this 的指向

  • 之后传入的参数表示函数执行所需的参数,区别在于 call 是直接传入参数,apply 是将参数放在数组中再传入

下面两个例子用于展示 call 和 apply 的作用

// 借用方法
let apple = {
    color: 'red',
    getColor: function() { return this.color }
}

let banana = {
    color: 'yellow'
}

let color = apple.getColor.call(banana) // apple.getColor.apply(banana)
console.log(color)

/*
 * 执行结果:
 * yellow
**/
// 实现继承
function Parent(name, age) {
    this.name = name
    this.age = age
    this.setName = function(name) { this.name = name }
    this.getName = function() { return this.name }
}

function Child(name, age) {
    Parent.call(this, name, age) // Parent.apply(this, [name, age])
}

let child = new Child('Peter')

child.setName('Steve')
let name = child.getName()
console.log(name)

/*
 * 执行结果:
 * Steve
**/

再来两个例子

// 判断类型,借用 Object.prototype.toString 方法
let number = 0
let string = ''
let boolean = true
let object = {}
let array = []

function typeOf(value) {
    return Object.prototype.toString.call(value).slice(8, -1)
}

console.log(typeOf(number))
console.log(typeOf(string))
console.log(typeOf(boolean))
console.log(typeOf(object))
console.log(typeOf(array))

/*
 * 执行结果:
 * Number
 * String
 * Boolean
 * Object
 * Array
**/
// 操作 arguments,借用 Array.prototype 中的方法
function addNumber() {
    let numbers = Array.prototype.filter.call(arguments, function(item) { // 过滤
        return typeof item === 'number'
    })
    let sum = numbers.reduce(function(prev, curr) { // 累加
        return prev + curr
    })
    return sum
}

let result = addNumber(1, 'a', 2, 'b', 3, 'c')
console.log(result)

/*
 * 执行结果:
 * 6
**/

2、bind

bind 的作用与 call、apply 大致相同,bind 的参数也和 call 完全相同,但是它们的区别如下:

  • call 和 apply 返回调用函数的返回值,bind 返回一个新的函数
  • call 和 apply 在调用后马上执行函数,而 bind 会返回一个新的函数,可以在需要的时候再调用
// 借用方法
let apple = {
    color: 'red',
    getColor: function() { return this.color }
}

let banana = {
    color: 'yellow'
}

let getColorForBanana = apple.getColor.bind(banana)
console.log(getColorForBanana)
let color = getColorForBanana()
console.log(color)

/*
 * 执行结果:
 * ƒ () { return this.color }
 * yellow
**/

【 阅读更多 JavaScript 系列文章,请看 JavaScript学习笔记

猜你喜欢

转载自www.cnblogs.com/wsmrzx/p/12180397.html