bind 返回一个函数, call apply 直接执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// bind
if ( !Function.prototype.bind ){
Function.prototype.bind = function(context){
if ( typeof this !== 'function' ){
console.log('this is not function');
throw new Error('this is not function');
return ;
}

var args = Array.prototype.slice.call(arguments, 1),
self = this;
var tmpFunc = function(){}; // 构造函数原型链继承
var mainFunc = function(){
var innerArgs = Array.prototype.slice.call(arguments); //改变上下文之后的arguments
var finalArgs = args.concat(innerArgs);
return self.apply(this instanceof tmpFunc ? this : context || window,finalArgs);
};

tmpFunc.prototype = this.prototype;
mainFunc.prototype = new tmpFunc();
return mainFunc;
};
}
1
2
3
4
5
6
7
8
9
10
11
12
13
// call, apply
Function.prototype.call = function(context){
var context = context || window;
context.fn = this;
var args = [];
for ( var i=0,len=arguments.length; i<len; i++ ){
args.push('arguments['+i+']');
}

var res = eval('context.fn('+args+')');
delete conetxt.fn;
return res;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// apply
Function.prototype.apply = function(context, argArr){
var context = context || window;
if ( !arr ) return this();

context.fn = this;

var args = [];
for ( var i=0,len=argArr.length; i<len; i++ ){
args.push('argArr['+i+']');
}

var res = eval('context.fn('+args+')');
delete conetxt.fn;
return res;
}