2021-01-14

this定义位置

JavaScript函数中的this不是在函数声明的时候定义的,而是在函数调用(即运行)的时候定义的

原型链

简单的回顾一下构造函数、原型和实例的关系:每个构造函数都有一个原型对象,原型对象都包含一个指向构造函数的指针,而实例都包含一个指向原型对象的内部指针。那么假如我们让原型对象等于另一个类型的实例,结果会怎样?显然,此时的原型对象将包含一个指向另一个原型的指针,相应地,另一个原型中也包含着一个指向另一个构造函数的指针。假如另一个原型又是另一个类型的实例,那么上述关系依然成立。如此层层递进,就构成了实例与原型的链条。这就是所谓的原型链的基本概念。

new 作用

function Foo(name) {
  this.name = name
  return this
}

function InjectNew() {
 var obj = {}
 obj.__proto__ = Foo.prototype
  return  Foo.call(obj, name)
}

截屏2021-01-18 下午8.44.31.png
截屏2021-01-18 下午8.44.44.png

手动实现call、bind、apply

call

Function.prototype.myCall = function(thisArgs, ...args){
  if(thisArgs === null || thisArgs === undefined){
    thisArgs = window
  }else{
    thisArgs = Object(thisArgs)
  }
  
   const specialMethod = Symbol("anything"); 
  thisArgs[specialMethod] = this
  var result = thisArgs[specialMethod](args)
  delete thisArgs[specialMethod]
  return result
}

apply

Function.prototype.myApply = function(thisArg) {
  if(thisArg === null || thisArg === undefined){
    thisArg = window
  }else{
    thisArg = Object(thisArg)
 }

  const key = Symbol()
  thisArg[key] = this
  

  let args = arguments[1]
  let result  
  if(args){
    if(Array.isArray(args)) {
      args = Array.from(args)
      result = thisArg[key](...args)
    }
  } else{
    result =thisArg[key]()
  }
return result
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容