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辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 数据类型 number string null undefined boolean symbol bigintsy...
    rub1cky阅读 300评论 0赞 0
  • const 类const成员通过构造函数初始化 const修饰的对象只能调用const修饰的函数,若类同时有con...
    东都哈士奇_cbef阅读 228评论 0赞 0
  • 我能相信什么? 任何一个实在的人,都是必须有所信的;同时这种信又必须是具体的。——关于信赖的具体与抽象,我们暂且用...
    雅典的咕隆咚阅读 462评论 0赞 0
  • 写在内置类原型上的方法,实例调用过的时候, 实例.xxx()xxx方法执行 ,方法中的this是要操作的实例向内置...
    44854e7904c5阅读 111评论 0赞 0
  • 久违的晴天,家长会。 家长大会开好到教室时,离放学已经没多少时间了。班主任说已经安排了三个家长分享经验。 放学铃声...
    飘雪儿5阅读 8,200评论 16赞 22

友情链接更多精彩内容