一 实现原理:https://segmentfault.com/a/1190000015724112?utm_source=sf-related
call和apply方法都是使用一个指定的this值和对应的参数前提下调用某个函数或方法。区别则在于call是通过传多个参数的方式。
1 Function.prototype.newApply = function (context, parameter) { 2 if (typeof context === 'object') { 3 context = context || window 4 } else { 5 context = Object.create(null); 6 } 7 let fn = Symbol(); // 保证对象属性的唯一性; 8 context[fn] = this; // 通过this获取call的函数(this指向调用者对象) 9 console.log(context); 10 context[fn](...parameter); 11 delete context[fn]; // 目的是保证使用完之后删除对应的属性; 12 } 13 let person = { 14 name: 'Abiel' 15 } 16 function sayHi(age, sex) { 17 console.log(this.name, age, sex); 18 } 19 sayHi.newApply(person, [25, '男']);
注意:封装的call 针对基本数据类型 Object.prototype.toString.call() 类型判断有一些小问题。