JavaScript 继承

1 通过prototype原型对象继承

function Hello(){
this.a = "吃饭了"
this.b = function(){
console.log("---------123")
}
}
function Test(){
this.c = function(){
console.log("-ccccccccccc")

}
}
Test.prototype = new Hello()
var test = new Test()
test.b()

2 通过构造器实现伪继承

function Hello(){
this.a = "吃饭了"
this.b = function(){
console.log("---------123")
}
}
function Test(){
this.c = function(){
console.log("-ccccccccccc")

}
this.d = Hello
this.d()
}
var test = new Test()
test.b()

3 使用apply或call实现伪继承

function Hello(name,age){
this.a = "吃饭了"
this.b = function(){
console.log("---------123")
}
}
function Test(name,age,content){
Hello.call(this,name,age)

//Hello.apply(this,[name,age])

this.content  = content
}
var test = new Test()
test.b()

4 动态的给对象增加属性和方法(现在知道什么是动态语言了么)

function Test(){

}

Test.prototype.a = function(){
  console.log('123')
}

Test.prototype.b = "good"
var test = new Test()
console.log("------>" + test.b )
test.a()

 

posted @ 2022-07-06 22:11  -和时间赛跑-  阅读(14)  评论(0编辑  收藏  举报