ES5实现
function mySymbol(obj) { var unique = (Math.random() + Date.now()).toString(32).slice(0, 16); if (obj[unique]) { return mySymbol(obj); } else { return unique; } }
Function.prototype.myCall = function (target) {
if (typeof this !== 'function') throw Error(this + 'is not a function');
target = target || window;
var args = [];
for (var i = 1; i < arguments.length; i++) { args.push('arguments[' + i + ']'); } var unique = mySymbol(target); target[unique] = this; eval('target[unique](' + args + ')'); delete target[unique]; }
|
ES6实现
Function.prototype.myCall = function (target = window) {
if (typeof this !== 'function') throw Error(this + 'is not a function');
const args = [...arguments].slice(1); const unique = Symbol('fn'); target[unique] = this; target[unique](...args); delete target[unique]; }
|
调用
function person(a, b) { console.log(a, b, this.name); }
var obj = { name: '靓仔' };
person.myCall(obj, '我', '是');
|
小提示
生成唯一值的目的是用来作为 target
的 key
,key
在对象中是不能出现重复的