bind的用法
1、生成新的函数
2、若生成的新函数作为构造函数,那么根传入的对象没有任何关系
3、可以作为偏函数使用
bind的js实现
if (!Function.prototype.bind) {
Function.prototype.bind = function(that) {
if (typeof this === 'function') {
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable')
}
var args = Array.prototype.slice.call(arguments,1);
var fToBind = this;
var fNop = function(){};
// 返回的Fbind作为new的构造函数时,生成的新对象作为this传入Fbind,新对象的__proto__就是fNop的实例
var Fbind = function() {
args = args.concat(Array.prototype.slice.call(arguments));
return fToBind.apply(this instanceof Fbind ? this : that, args);
}
// 维持原型链
if (this.prototype) {
fNop.prototype = this.prototype;
}
Fbind.prototype = new fNop();
return Fbind;
}
}
call实现
Function.prototype.call = function(that) {
if (typeof this !== 'function') {
throw new TypeError('Function.prototype.call-----is not a function');
}
var args = [...arguments].slice(1);
that.fn = this;
var result = that.fn(...args);
Reflect.deleteProperty(that, 'fn');
return result;
}
apply实现
Function.proptotype.apply = function() {
if (typeof this !== 'function') {
throw new TypeError('Function.prototype.apply-----is not a function');
}
that.fn = this;
var result =
arguments[1]
? that.fn(...arguments[1])
: that.fn();
Reflect.deleteProperty(that, 'fn');
return result;
}