<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
/* 原型链继承
1套路:
1.定义父类型构造函数
2.给父类型的原型添加方法
3.定义子类型的构造函数
4.创建父类型的对象赋值给子类的原型
5.将子类型原型的构造属性给子类型
6.给子类型原型添加方法
7.创建子类型的对象,可以调用父类型的方法 */
//父类型
function Supper(){
this.supProp ="Supper property"
this.fn = function(){
return this.subProp
}
}
Supper.prototype.showSupperProp = function(){ //!!Supper的实例可以看到这个方法(因为Supper的实例有一个__proto__属性值指向了Supper的原型对象)
console.log(this.supProp)
}
//子类型
function Sub(){
this.Sub ="Sub property"
}
Sub.prototype.showSubProp = function(){
console.log(this.subProp)
}
//目标,sub访问showSupperProp
Sub.prototype = new Supper() //!!将子类的原型指向父类型的实例对象,就可以看到父类的共有方法.
//修复
Object.defineProperty(Sub.prototype,'constructor',{
value:Sub
})
var sub = new Sub()
sub.showSupperProp() //打印Supper property
console.log(sub.constructor) //修复后 是打印 sub(){....}
/* 借用构造函数继承(假的)
1.套路:
1定义父类型的构造函数
2定义子类型的构造函数
3在子类型的构造函数中调用父类型构造
2.关键:
1在子类型中通用super()调用父类型构造函数 */
function Person(name, age){
this.name = name //this是动态指定的
this.age =age
}
function Student(name, age, price){
Person.call(this, name, age) //相当于this.Person(name,age)//借用了Person的构造函数 ,call借用执行,谁来执行?this ,实际有继承吗?没有.实际就是简化代码
this.price = price
}
var s = new Student('Tome', 20, 120000)
console.log(s.name, s.age, s.price) //Tome, 20 120000
/* 组合继承(原型链+使用构造函数的组合继承)
1.利用原型链实现对父类型对象的方法继承
2.利用super借用父类型构造函数初始化相同属性
*/
function Person(name, age){
this.name = name //this是动态指定的
this.age =age
}
Person.prototype.setName =function(name){
this.name = name
}
function Student(name, age, price){
Person.call(this, name, age) // 为了得到属性
this.price = price
}
Student.prototype = new Person() //为了能看到父类型的方法
Object.defineProperty(Student.prototype,'constructor',{
value:Student
})
var s1 = new Student('Alice' , 20, 10000)
console.log(s1.name, s1.age, s1.price) //Alice 20 10000
s1.setName("Bob")
console.log(s1.name) //Bob
</script>
</body>
</html>