记录手写call时的一些东西

361 阅读1分钟

手写call

Function.prototype.myCall = function (context, ...args) {
   context = context || window
   const fn = Symbol()
   context[fn] = this
   context[fn](...args)
   
   delete context[fn]
}

我自己不是很习惯对象这样写 context[fn] 于是改成context.fn
然后发现新加的方法并没有被删除
原来关于Symbol有两个要注意的点。
1.不能new
2.不能直接对象.symbol

顺便搜索了下Symbol的作用
1.当一个复杂对象属性很多的时候,很容易把某个属性名覆盖掉。
2.模拟类的私有方法。
因为ES6的class是没有private关键字来定义私有方法和私有变量。 可以利用Symbol的唯一性。

再手写下apply

Function.prototype.myApply = function (context, args) {
   context = context || window
   const fn = Symbol()
   context[fn] = this
   context[fn](...args)
   
   delete context[fn]
}