bind
bind使用
function ff() {
console.log(this, arguments)
return '';
}
// 默认调用
ff(1,2,3) // this: windows arguments: [1,2,3]
// bind
// 方法不会执行
var bindFF = ff.bind({n: 'n'}, 'a', 'b');
// 调用时才会执行
bindFF('c', 'd'); // // this: {n: 'n'} arguments: ['a', 'b', 'c', 'd']
// bind使用
setTimeOut(window.addEventListener.bind(window, 'resize', ff), 0)
// 等同于
var bindFF = window.addEventListener.bind(window, 'resize', ff)
// bindFF => window.addEventListener('resize', ff)
setTimeOut(bindFF, 0)
手写bind实现
Function.prototype.mybind = function(asThis) {
// 缓存参数
var slice = Array.prototype.slice;
// bind方法获取的参数
var args = slice.call(arguments, 1);
var fn = this;
// this指向判断
if(typeof fn !== 'function') {
throw new Error('调用方法this必须是一个函数')
}
// 返回一个方法:执行之前的方法
// 拼接后续参数
function inner() {
// 判断当前函数是否是new
var isNew = this.constructor === inner;
var innerArgs = slice.call(arguments);
// 数组拼接
args = args.concat(innerArgs);
// new出来传函数this 不是传之前参数
return fn.apply(isNew ? this : asThis, args);
}
return inner;
}
function ff() {}
// 1、函数使用
var newFF = ff.mybind({name: 'zhangsan'}, 'x', 'y', 'z');
newFF('x1', 'y1');
// 2、构造函数使用
var newFF2 = ff.mybind({name: 'zhangsan'}, 'x', 'y', 'z');
var instance = new newFF2('z1', 'z2'); // this.constructor 指向 newFF2 => inner