javascript原型,繼承

//普通對象
//函數對象(有原型 prototy 的屬性)
//原型的應用 繼承
function Amial(){
    this.type = '小於'
}
function cat(name){
    this.name = name
}
cat.prototype = new Amial()
var cat1 = new cat('小張')
console.log(cat1.name,cat1.type)

//構造器  繼承 缺點:把父元素的屬性都複製了
function Amial(){
    this.type = '動物'
}
function amm(name){
    Amial.apply(this) //調用Amial構造器 Amial == amm
    //Amial.call(this,x,y,z)  Amial.apply(this,[x,y,z])
    this.name = name
}
var a = new amm('張三')
console.log(a.type)

//組合繼承(原型+構造器) 缺點:調用兩次父類構造器

function Preson(name){
    this.arr = ['js','php']
    this.name = name
}
Preson.prototype.showname = function(){
    console.log(this.name)
}
function teacher(name,gread){
    Preson.call(this,name)
    this.gread = gread
}
teacher.prototype = new Preson() // 最關鍵的一句
var a = new teacher('xiaoming', 23)
console.log(a.arr,a.name,a.gread)
a.showname()

//原型+構造+寄生
function father(name){
    this.arr = ['aa','bb']
    this.name = name
}
father.prototype.showname = function(){
   console.log(this.name)
}
function son(name,course){
   father.call(this,name)
   this.course = course
}
function extend(subobj,superobj){
   var proobj = Object.create(superobj.prototype)
   subobj.prototype = proobj
}
extend(son, father)
var a = new son('xiaoming', 23)
console.log(a.arr,a.name,a.course)
a.showname()
相關文章
相關標籤/搜索