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;
}
複製程式碼