JS中的繼承

//返回一個(gè)對(duì)象,該對(duì)象的原型為傳入的參數(shù)o,低版本使用
function createObject(o) {
  function Fn() {}
  Fn.prototype = o
  return new Fn()
}

//繼承函數(shù)
function inheritPrototype(SubType, SuperType) {
  SubType.prototype = Object.create(SuperType.prototype) //創(chuàng)建一個(gè)對(duì)象,使其指向原型指向父類的原型,將該對(duì)象作為子類函數(shù)的原型對(duì)象
  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)


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 【前言】 近來因?yàn)橹v課需要,涉及到使用JavaScript中的繼承,但發(fā)現(xiàn)遇上不懂的同學(xué),無法用一句話帶過,因?yàn)橹?..
    陌染007閱讀 154評(píng)論 0 1
  • 回想起剛?cè)腴TJS的時(shí)候,初次接觸JS原型繼承,令我頭大,心想啊,為什么要把繼承搞得這么復(fù)雜。隨著時(shí)間推移,學(xué)習(xí)源碼...
    forJavascript閱讀 428評(píng)論 2 1
  • 在了解了js 中的原型鏈之后 (http://www.itdecent.cn/p/1e683a9771c3),我...
    施主畫個(gè)猿閱讀 352評(píng)論 0 1
  • 1.原型鏈繼承,javasrcipt實(shí)現(xiàn)繼承的基本思想:通過原型將一個(gè)應(yīng)用類型引用另一個(gè)引用類型的屬性和方法。 2...
    瑾年Web閱讀 260評(píng)論 0 0
  • 繼承 原型鏈繼承 實(shí)現(xiàn) 隱含的問題 如果有屬性是引用類型的,一旦某個(gè)實(shí)例修改了這個(gè)屬性,所有實(shí)例都會(huì)受到影響 創(chuàng)建...
    南楓小謹(jǐn)閱讀 186評(píng)論 0 0

友情鏈接更多精彩內(nèi)容