Closed CatsAndMice closed 2 years ago
call/apply唯一区别: 传参类型不同
Function.prototype.myCall = function (self, params) { let isNull = self === null; let isUndefind = self === undefined let name = this.name; let type = typeof self if (isNull || isUndefind) { self = globalThis; } if (type === "string") { self = new String(self) } if (type === "number") { self = new Number(self) } self[name] = this; params ? self[name](params) : self[name](params); } Function.prototype.myApply = function (self, params) { let isNull = self === null; let isUndefind = self === undefined let name = this.name; let type = typeof self if (isNull || isUndefind) { self = globalThis; } if (type === "string") { self = new String(self) } if (type === "number") { self = new Number(self) } self[name] = this; params ? self[name](...params) : self[name](); } function fn() { console.log(name, this.name); } function fn1(params1, params2) { console.log(params1, params2, this); } let obj = { name: 'myCall' } let name = 'name' fn.myCall(null) fn1.myApply(null,[1,2])
call/apply唯一区别: 传参类型不同