BIND & CALL & APPLY
1
%
bind
bind()
创建了一个新函数,调用这个新函数时,其 this
被指定为 bind()
第一个参数,剩余参数作为新函数的参数
1
%
call
call()
方法使用指定的 this
值和单独给出的一个或多个参数来调用一个函数,使用参数列表形式
1
%
apply
apply()
方法调用给定this
值的函数,使用数组(或类似数组对象)作为参数
BIND
4/5
1. 语法 function.bind(this,args,…)
2. 用法
// 定义一个 personA 对象
let personA = { age : 100, getAge: function(){ return this.age; } }
// 定义一个 personB 对象
let personB = { age : 10, getAge: function(){ return this.age; } }
// 调用 person 对象的方法
personA.getAge();
// 声明 personC
let personC = personA.getAge;
// 绑定不同的对象
let bindPersonA = personC.bind(personA)
let bindPersonB = personC.bind(personB);
console.log(bindPersonA()); // 100
console.log(bindPersonB()); // 10
手动实现一个 bind
3/5
Function.prototype.myBind = function(){
if(typeof this !== ‘function’){
throw new Error(‘TYPE ERROR’)
}
const that = this;
const args = […arguments].slice(1);
return function BT(){
if(this instanceof BT){
return new that(…args,…arguments)
}
return that.apply(context,args.concat(…arguments))
}
}
CALL
4/5
1. 语法 function.call(this,args,…)
2. 用法 使用 call 实现继承
// 定义父
function Parent(age){
this.age = age;
}
// 定义子
function Child(age,name){
Parent.call(this,age);
this.name = name
}
let child = new Child(12,’Lee’)
console.log(child); // { age: 12, name: ‘Lee’ }
手动实现一个 call
4/5
Function.prototype.myCall = function(context){
if(typeof this !== ‘function’ ){
throw new Error(‘TYPE ERROR,NOT FUNCTION’)
}
// 获取上下文
context = context || window;
// 添加 fn 属性
context.fn = this;
// 获取参数数组
let args = […arguments].slice(1);
// 处理调用
let results = context.fn(args)
// 删除 fn
delete context.fn;
// 返回结果集
return results
}
APPLY
5/5
1. 语法 function.apply(this,[argsArray])
2. 用法 使用 apply 比较大小
// 定义一个 1-10000 的数组
const numbers = new Array(10000).fill()
.map((_,index) => index +1);
// Math 工具函数
let max = Math.max.apply(null, numbers);
let min = Math.min.apply(null, numbers);
手动实现一个 apply
3/5
Function.prototype.myApply = function(args){
if(typeof this !== ‘function’){
throw new Error(‘TYPE ERROR’)
}
args = args || window;
args.fn = this;
let results;
if(arguments[1]){
results = args.fn(arguments[1])
} esle {
results = args.fn()
}
return results;
}