/* let foo = { a: 10, bar: function(name,age) { console.log(name, age); console.log(this.a); } } foo.bar();//10 */
Function.prototype.call2 = function (context) { let _context = context || window; _context.fn = this; let arg = []; for (let i = 1; i < arguments.length; i++) { arg.push(arguments[i]) } let res = _context.fn(...arg); delete _context.fn; return res; }
Function.prototype.apply2 = function (context) { let _context = context || window; _context.fn = this; if (Array.isArray(arguments[1])) { let res = _context.fn(...arguments[1]); delete _context.fn; return res; } elseif (arguments[1]) { thrownewError('need array'); } else { let res = _context.fn(); delete _context.fn; return res; } }
Function.prototype.bind2 = function (context) { let self = this; //self === bar let arg = Array.prototype.slice.call(arguments, 1); let fbound = function () { let bindArg = Array.prototype.slice.call(arguments); //当作为构造函数时,this 指向实例,self 指向绑定函数(bar), //因为下面一句 `fbound.prototype = this.prototype;`,已经修改了 fbound.prototype 为 绑定函数(bar)的 prototype, //此时结果为 true,当结果为 true 的时候,this 指向实例。