call、apply、bind的区别,欢迎指正。
console.log('---------------------call/apply/bind区别---------------------')
// call/apply/bind区别
let Fcall = function(name) {
this.name = name
this.say = function() {
console.log(this.name)
}
this.say()
}
var fcall = {}
Fcall.call(fcall,'che-call') // 参数一个传,立即执行 che-call
Fcall.apply(fcall,['che-apply']) // 参数数组传,立即执行 che-apply
var bin = Fcall.bind(fcall,'che-bind') // bind不会立即执行,会返回函数 undefined
bin() // 返回后的函数需要手动执行 che-bind
// 应用
let array = [1, 7, 5]
let max = Math.max.apply(null, array); // 取数组最大值 7
let min = Math.min.apply(null, array); // 取数组最小值 1
let max1 = Math.max(...array) // es6+简洁版求数组最大值、跟本知识无关 7
let min1 = Math.min(...array) // es6+简洁版求数组最小值、跟本知识无关 1
console.log(max , min, max1, min1) // 7 1 7 1
let arr1 = [1, 2];
let arr2 = [4, 5];
Array.prototype.push.apply(arr1, arr2); // 数组合并,但是改变了arr1,不推荐
let arres6 = [...arr1,...arr2] // es6简洁版合并, 不会改变原数组
console.log(arr1, arres6); // arr1 [1, 2, 4, 5] arres6 [1, 2, 4, 5, 4, 5]