Function.prototype.bind2 = function(context) { const args = Array.prototype.slice.call(arguments, 1); // 获取除绑定的this参数之外的其他参数 const self = this; var fBind = function() { return self.apply(this instance fBind ? this : context, args.concat(Array.prototype.slice.call(arguments))); // this instance fBind ? this : context为判断fBind是否作为构造函数调用,如果是则将this指向实例,否则this指向context参数。 } fBind.prototype = Object.create(self.prototype); return fBind;}复制代码
// new 为关键字,只模拟功能实现,不模拟具体调用,最后调用为new2(constructor, params1, params1);function new2() { var constructor = Array.prototype.shift(arguments); // 获取构造函数,并且shift会改变arguments var obj = new Object(); obj.__proto__ = constructor.prototype; // 加入原型链 var result = constructor.apply(obj, arguments); return typeof result === 'object' ? result : obj; // 构造如果显示return一个对象,则返回该对象,否则返回this;}复制代码
// instanceof(x, y)function instanceof(x, y) { while(x.__proto__!==null) { if(x.__proto__===y.prototype) { return true; break; } x.__proto__ = x.__proto__.proto__; } if(x.__proto__==null) { return false;}}复制代码
// Object.assignObject.defineProperty(Object, assgin2, { wirte: true, configurable: true, enumerable: false, value(target) { if (target == null) throw new TypeError('Cannot convert undefined or null to object'); const results = typeOf target === 'Object' ? target : Object(target); if (arguments.length > 1) { for (let i = 1; i < arguments.length; i += 1) { const arg = arguments[i]; if (arg !== null) { const obj = typeOf arg === 'Object' || 'Function' ? arg : Object(arg); // 简单类型会被包装成对象类型 for (const k in obj) { if (Object.prototype.hasOwnProperty(obj, k)) { results[k] = obj[k] } } } } } return results; }})复制代码