手写实现call方法
实现步骤:
1、将函数设为对象的属性
2、执行该函数
3、删除该函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| Function.prototype.call = function (context) { var context = context || window; context.fn = this;
var args = []; for(var i = 1, len = arguments.length; i < len; i++) { args.push('arguments[' + i + ']'); }
var result = eval('context.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);
console.log(bar.call(obj, 'kevin', 18));
|