- 需要了解的知识点
symbol 这是一种新的基础数据类型 ES6引入的新特性
应用场景:
1、使用Symbol来作为对象属性名(key)
2、使用Symbol来替代常量
3、使用Symbol定义类的私有属性/方法
参考博客 https://www.jianshu.com/p/f40a77bbd74e
- 基础版
Function.prototype.myCall = function (context,...arg){
const fn = Symbol('临时属性'); //调用Symbol()函数时传入一个可选的字符串参数,相当于给你创建的Symbol实例一个描述信息
context[fn] = this;
context[fn](...arg);
delete context[fn]
}
实现思路
- 通过对象属性的方式调用函数,这个函数里面的this指向这个对象
- 每次调用新增 一个symbol属性,调用完删除
- 这个symbol属性就是调用mycall方法的函数
- 函数形参中使用…ary是将多个形参都放到了一个数组里,在函数内部使用arg这个变量时,就是包含所有形参的数组
- 在调用context fn时候,…arg是为了展开数组,依次传入参数调用函数
参考文章 https://segmentfault.com/a/1190000020044435
apply()
Function.prototype.myApply = function(context,arg){
const fn = Symbol('临时属性');
context[fn] = this;
context[fn](...arg);
delete context[fn];
}
const obj = {
a:1
}
test.myApply(obj2,[2,3,4])
bind
Function.prototype.myBind = function (objThis, ...params) {
const thisFn = this; // 存储源函数以及上方的params(函数参数)
// 对返回的函数 secondParams 二次传参
let fToBind = function (...secondParams) {
console.log('secondParams',secondParams,...secondParams)
const isNew = this instanceof fToBind // this是否是fToBind的实例 也就是返回的fToBind是否通过new调用
const context = isNew ? this : Object(objThis) // new调用就绑定到this上,否则就绑定到传入的objThis上
return thisFn.call(context, ...params, ...secondParams); // 用call调用源函数绑定this的指向并传递参数,返回执行结果
};
fToBind.prototype = Object.create(thisFn.prototype); // 复制源函数的prototype给fToBind
return fToBind; // 返回拷贝的函数
}