关于原型的问题

来源:5-5 instanceof 是基于原型链实现的

慕虎2023661

2023-07-05

  function Person(name) {
    this.name = name
    this.showName = function () {
      console.log(this.name)
      return this.name
    }
  }
  console.log('Person')
  console.dir(Person)

  class Person1 {
    showName() {
      console.log(this.name)
      return this.name
    }
  }
  console.log('Person1')
  console.dir(Person1)

图片描述
如上图代码所示,
我们都知道,构造函数Person的prototype属性指向浏览器内存中创建的原型对象(Person.prototype),
通过构造函数Person创建的原型对象(Person.prototype)没有showName方法
而通过class生成的原型对象(Person1.prototype)中有showName方法
请问,这是什么原因。
构造函数必须使用Person.prototype.showName = ... 才和 class效果相同

写回答

1回答

双越

2023-07-06

通过构造函数Person创建的原型对象(Person.prototype) —— 这句话没看懂


整体看着也很懵,你可以通过代码注释的形式来描述问题,多配合代码来展示。

0
2
双越
回复
慕虎2023661
class 中写一个 fn ,相当于构造函数写一个 prototype.fn (而不是 this.fn)
2023-07-07
共2条回复

一天时间高效准备前端技术一面 匹配大厂面试要求

针对时下面试高频考点,帮助新人js面试快速通关

4694 学习 · 1681 问题

查看课程