apply & call & bind 源码
- call 源码
- eval 是全局对象上的一个函数,会把传入的字符串当做 JavaScript 代码执行。如果传入的参数不是字符串,它会原封不动地将其返回
Function.prototype.call = function(context) {
var context = context || window;
context.fn = this;
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push('arguments[' + i + ']');
}
var result = eval('context.fn('+args+')');
delete context.fn;
return result;
}
Function.prototype.apply = function(context, arr) {
var context = Object(context) || window;
context.fn = this;
var result;
if (!arr) {
result = context.fn();
} else {
var args = [];
for (var i = 0; i < arr.lenght; i++) {
args.push('arr['+ i + ']');
}
result = eval('context.fn('+ args +')');
}
delete context.fn;
return result;
}
Function.prototype.bind = function (context) {
var ctx = context;
if (typeof ctx !== 'function') {
throw new TypeError('Type Error!');
}
var self = this;
function fn() {};
fn.prototype = this.prototype;
var bound = function(args) {
return self.apply(context, args || null);
}
bound.prototype = new fn();
return bound;
}