JS中的继承

//返回一个对象,该对象的原型为传入的参数o,低版本使用
function createObject(o) {
  function Fn() {}
  Fn.prototype = o
  return new Fn()
}

//继承函数
function inheritPrototype(SubType, SuperType) {
  SubType.prototype = Object.create(SuperType.prototype) //创建一个对象,使其指向原型指向父类的原型,将该对象作为子类函数的原型对象
  Object.defineProperty(SubType.prototype, "constructor", {
    enumerable: false,
    configurable: true,
    writable: true,
    value: SubType
  })
}

function Person(name, age, friends) {
  this.name = name
  this.age = age
  this.friends = friends
}

Person.prototype.running = function() {
  console.log("running~")
}

Person.prototype.eating = function() {
  console.log("eating~")
}


function Student(name, age, friends, sno, score) {
  Person.call(this, name, age, friends)
  this.sno = sno
  this.score = score
}

inheritPrototype(Student, Person)

Student.prototype.studying = function() {
  console.log("studying~")
}

var stu = new Student("why", 18, ["kobe"], 111, 100)
console.log(stu)
stu.studying()
stu.running()
stu.eating()

console.log(stu.constructor.name)


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 【前言】 近来因为讲课需要,涉及到使用JavaScript中的继承,但发现遇上不懂的同学,无法用一句话带过,因为周...
    陌染007阅读 1,238评论 0 1
  • 回想起刚入门JS的时候,初次接触JS原型继承,令我头大,心想啊,为什么要把继承搞得这么复杂。随着时间推移,学习源码...
    forJavascript阅读 3,030评论 2 1
  • 在了解了js 中的原型链之后 (https://www.jianshu.com/p/1e683a9771c3),我...
    施主画个猿阅读 2,435评论 0 1
  • 1.原型链继承,javasrcipt实现继承的基本思想:通过原型将一个应用类型引用另一个引用类型的属性和方法。 2...
    瑾年Web阅读 1,634评论 0 0
  • 继承 原型链继承 实现 隐含的问题 如果有属性是引用类型的,一旦某个实例修改了这个属性,所有实例都会受到影响 创建...
    南枫小谨阅读 1,342评论 0 0

友情链接更多精彩内容