Function.prototype.myApply = function(context) { if (typeofthis !== 'function') { thrownewTypeError('Error') } context = context || window context.fn = this let res if (!arguments[1]) { res = context.fn() } elseif (arguments[1].constructor.name === 'Array') { res = context.fn(...arguments[1]) } else { returnconsole.error('Uncaught TypeError: CreateListFromArrayLike called on non-object') // throw 'Uncaught TypeError: CreateListFromArrayLike called on non-object' } delete context.fn return res }
bind:
Function.prototype.myBind = function() { var self = this// 保存原函数 var args = Array.prototype.slice.call(arguments) // 参数转为数组 // var args = [...arguments].slice(1) // 参数转为数组 var context = args.shift() // 保存需要绑定的this上下文 returnfunction() { // 返回一个新函数 self.apply(context, args.concat([].slice.call(arguments))) } }
// a instanceof b b.prototype 是否在 a 的原型链中 functionmyInstanceof(a, b) { if (typeof a === 'object' || a === null) returnfalse
// getProtypeOf是Object对象自带的一个方法,能够拿到参数的原型对象 let proto = Object.getPrototypeOf(a) while (true) { // 查找到尽头,还没找到 if (proto == null) returnfalse // 找到相同的原型对象 if (proto == b.prototype) returntrue proto = Object.getPrototypeof(proto) } }