1. 语法
1.1 Function.property.apply()
apply()方法调用一个函数,其具有一个指定的this值,以及作为一个数组(或类似数组的对象)提供的参数
function.apply(thisArg,[argsArray])
1.2 Function.property.call()
call()方法调用一个函数,其具有一个指定的this值,和提供的参数列表
function.call(thisArg,arg1,arg2...)
1.3 Function.property.bind()
bind()方法创建一个新函数,当被调用时,将其this关键字设置为提供的值,在调用新函数时,提前提供一个给定的参数序列
function.bind(thisArg,队列or数组)()
2. 用法
2.1 普通写法
var me = {
name: "zhangsan",
sayHello: function(age){
console.log("I am", this.name + " " + age + "years old")
}
}
var someone = {
name: "someone",
}
me.sayHello(24); // I am zhangsan 24 years old
2.2 apply和call方法
me.sayHello.apply(someone,[24]);
// I am someone 24 years old
me.sayHello.call(someone,24);
// I am someone 24 years old
call和apply第一个参数是要绑定上下文,后面参数要传给调用该方法的函数。区别在于apply参数是数组,call参数是逐个列出的
2.3 bind方法
me.sayHello.bind(someone,24)() // I am someone 24 years old
me.sayHello.bind(someone,[24]()
// 也可以这样写
me.sayHello.bind(sonmeone)(24)
me.sayHello,bind(someone)([24])
bind方法传递给调用函数的参数可以逐个列出,也可以写成数组。bind与call、apply区别是,bind返回了绑定上下文的函数,call、apply直接执行了函数。
bind方法会构建一个新的函数,称为绑定函数,该函数会以创建它时传入bind()的第一个参数作为this,传入后面的参数及绑定函数运行时本身的参数按顺序作为原函数的参数来调用原函数
3. 应用场景
3.1 求数组中最值
let arr = [1,4,6,45,234]
let max = Max.math.apply(null, arr)
let min = Min.math.apply(null, arr)
3.2 将类数组转化为数组
let trueArr = Array.prototype.slice.call(arrayLike)
3.3 数组追加
let arr1 = [1,2,3]
let arr2 = [4,5,6]
let total = [].push.apply(arr1,arr2)
console.log(total) // 6
console.log(arr1) // [1,2,3,4,5,6]
console.log(arr2) // [4,5,6]
Array.prototype.push():将指定的元素添加到数组的末尾,并返回新的数组长度。
3.4 判断变量类型
function isArray(obj){
return Object.prototype.toString.call(obj) == '[object Array]'
}
isArray([]) // ture
isArray('dot') // false
3.5 利用call和apply做继承
function Persion(name,age){
// this都指向实例
this.name=name
this.age=age
this.sayAge=function(){
console.log(this.age)
}
}
function Female(){
Persion.apply(this.arguments)
// 将父元素的方法在这里执行一遍就继承了
}
var a = new Female('小红',18)
3.6 使用log代理console.log
function log(){
console.log.apply(console, arguments);
}
// 亦或let log = console.log()
总结
三者都可以改变函数的this的指向;如果没有传递第一个参数,this 的值将会被绑定为全局对象,严格模式下this的值是null或undefined(如下);bind是返回对应函数以便稍后调用,apply、call是立即执行
var sData = 'Wisen';
function display() {
console.log('sData value is %s ', this.sData);
}
display.call(); // sData value is Wisen