javascript系列之 bind的模拟实现 篇
1. bind的基本用法
bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
--MDN
var bar = {
age: 18
}
function foo(name, sex) {
console.log(name);
console.log(sex);
console.log(this.age)
}
var bindFoo = foo.bind(bar)
bindFoo('Joker', 'male');
var bindFoo = foo.bind(bar, 'joker')
bindFoo();
bindFoo('male');
var bar = {
age: 18
}
foo.prototype.color = 'red';
function foo(name, sex) {
this.major = "internet"
console.log(name);
console.log(sex);
console.log(this.age)
}
var bindFoo = foo.bind(bar, 'joker')
var newBindFoo = new bindFoo('male')
console.log(newBindFoo.color)
console.log(newBindFoo.major)
2. bind的模拟实现
- 合并参数
- 判断是否作为构造函数
- 修改this指向
Function.prototype.myBind = function (target) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
return function () {
bindArgs = Array.prototype.slice.call(arguments);
finalArgs = args.concat(bindArgs)
return self.apply(target, finalArgs);
}
}
var bindFoo = foo.myBind(bar, 'joker');
bindFoo('male');
Function.prototype.myBind = function(target) {
var self = this;
var args = [].slice.call(arguments, 1);
var fBound = function () {
var bindArgs = [].slice.call(arguments);
var finalArgs = args.concat(bindArgs);
return self.apply(this instanceof fBound ? this : self, finalArgs)
}
fBound.prototype = self.prototype;
return fBound;
}
var bindFoo = foo.myBind(bar, 'joker')
var newBindFoo = new bindFoo('male')
console.log(newBindFoo.color)
console.log(newBindFoo.major)
Function.prototype.myBind = function(target) {
var self = this;
var args = [].slice.call(arguments, 1);
var fBound = function () {
var bindArgs = [].slice.call(arguments);
var finalArgs = args.concat(bindArgs);
return self.apply(this instanceof fBound ? this : self, finalArgs)
}
function Empty () {};
Empty.prototype = self.prototype;
fBound.prototype = new Empty();
return fBound;
}
var bindFoo = foo.myBind(bar, 'joker')
var newBindFoo = new bindFoo('male')
console.log(newBindFoo.color)
console.log(newBindFoo.major)