我们知道apply call bind 都是改变this的指向的,我们首先看apply call的实现。
call的一般使用如下
var foo = {
value: 1
};
function bar() {
console.log(this.value);
}
bar.call(foo); // 1
我们可以通过什么方式来模拟call方法呢?
var foo = {
value: 1,
bar: function() {
console.log(this.value)
}
};
foo.bar(); // 1
我们可以看到只有这个bar函数再foo内,我们foo.bar()执行效果正是我们所需要的。所以我们可以通过给foo对象增加bar方法,执行之后再删除就可达到我们的需求。
1. foo.fn = bar
2. foo.fn()
3. delete foo.fn
所以我们可以这样实现
var foo = {
value: 1
};
function bar() {
console.log(this.value);
}
bar.call(foo);
Function.prototype.call = function (obj) {
obj.fn = this; // 这个this就是那个函数调用了call就指向哪个函数,具体可以看我分析的this的使用的第二种情况的例子2
obj.fn()
delete obj.fn;
}
因为call函数是被bar函数调用的,所以这个属性应该是在Function.prototype
上。上述实现可以满足基本需求,我们还需要可以传参数。
Function.prototype.call = function(obj) {
var arg = Array.from(arguments).slice(1)
obj.fn = this;
obj.fn(...arg);
delete obj.fn;
}
var foo = {
value: 1
};
function bar(a, b) {
console.log(a)
console.log(b)
console.log(this.value);
}
bar.call(foo, 'hellow','word');
上述我也ES6的扩展运算符...,如果不是呀ES6该如何实现呢?
首先我们知道函数的所有参数不能放在一个数组中去传递,我们可以使用这种方式
var args = [];
for(var i = 1, len = arguments.length; i < len; i++) {
args.push('arguments[' + i + ']');
}
// 执行后 args为 ["arguments[1]", "arguments[2]", "arguments[3]"]
eval('obj.fn(' + args +')')
eval('context.fn(' + args +')')
args 会自动调用 Array.toString() 这个方法。
- 那为什么我们不直接
obj.fn(args.toString())
呢? - 为什么不直接Array.from(arguments)而是需要把args拼凑成如此内容的数组呢?
eval的作用就是把字符串当成js来解析执行。
第一个问题: [1,2,3].toString()的结果为字符串'1,2,3'。obj.fn('1,2,3')
的结果就是给obj.fn
传递了一个参数'1,2,3'
。我们想要的到的效果为obj.fn(1,2,3)
。所以不能直接obj.fn(args.toString())
。
第二个问题,首先我们看如下代码
var a = 'kevin';
function fn(o) {
console.log(o)
};
eval('fn(' + a + ')');
在这个例子下, eval('fn(' + a + ')')
; 相当于执行fn(kevin)
,注意不是 fn('kevin')
,kevin
为一个变量,就会报错。
所以如果我们直接传递Array.from(arguments)
在eval
解析执行的时候会报错,所以我们需要在eval运行时再取值arguments[1]
这个是可以取到值得,并不会报错。
还有一些小点没有实现
- this 参数可以传 null,当为 null 的时候,视为指向window
- 函数是可以有返回值的
Function.prototype.call = function (obj) {
var obj = obj || window; // 新增
obj.fn = this;
var args = [];
for(var i = 1, len = arguments.length; i < len; i++) {
args.push('arguments[' + i + ']');
}
var result = eval('obj.fn(' + args +')');
delete context.fn
return result; // 新增
}
// 测试一下
var value = 2;
var obj = {
value: 1
}
function bar(name, age) {
console.log(this.value);
return {
value: this.value,
name: name,
age: age
}
}
bar.call(null); // 2
console.log(bar.call2(obj, 'kevin', 18));
apply的实现
apply
的实现跟call的实现几乎一致,只是apply
的参数是数组,循环的是参数数组不用arguments
了。
call, apply的实现
bind的实现
bind() 方法会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数。
所以bind和apply,call的主要区别是返回一个函数,调用这个返回函数才改变this。
var foo = {
value: 1
};
function bar() {
console.log(this.value);
}
var bindFoo = bar.bind(foo); // 返回了一个函数
bindFoo(); // 1
bind的简易实现
Function.prototype.bind = function (obj) {
var that = this; // 注意this的指向,需要var that = this
return function () {
that. apply(obj)
}
}
我们的bind是可以传递参数的
var foo = {
value: 1
};
function bar(name, age) {
console.log(this.value);
console.log(name);
console.log(age);
}
var bindFoo = bar.bind(foo, 'daisy');
bindFoo('18');
// 1
// daisy
// 18
可以看到bind的返回函数仍然可以传递参数
Function.prototype.bind = function (obj) {
var self = this;
// 获取bind2函数从第二个参数到最后一个参数
var args = Array.prototype.slice.call(arguments, 1);
return function () {
// 这个时候的arguments是指bind返回的函数传入的参数
var bindArgs = Array.prototype.slice.call(arguments);
return self.apply(obj, args.concat(bindArgs));
}
}
bind的返回函数可以当做构造函数使用,当 bind 返回的函数作为构造函数的时候,bind 时指定的 this 值会失效,但传入的参数依然生效
var value = 2;
var foo = {
value: 1
};
function bar(name, age) {
this.habit = 'shopping';
console.log(this.value);
console.log(name);
console.log(age);
}
bar.prototype.friend = 'kevin';
var bindFoo = bar.bind(foo, 'daisy');
var obj = new bindFoo('18');
// undefined
// daisy
// 18
console.log(obj.habit);
console.log(obj.friend);
这个时候的 this
已经指向了obj
,如果bar函数内有this.value = 'ddd',
那么console.log(this.value)
;就会为ddd
。
Function.prototype.bind = function (obj) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
var fNOP = function () {};
var fBound = function () {
var bindArgs = Array.prototype.slice.call(arguments);
return self.apply(this instanceof fNOP ? this : obj, args.concat(bindArgs));
}
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
}