面向对象编程——继承性
将对象得属性和方法进行传递 原型链,改变this得指向性问题
三种继承方式,将以实例演示:
“创建一个人类然后继承学生类以及教师类”
function Human(name,age){
this.name=name
this.age=age
}
Human.prototype.move=function(){
console.log(this.name+'在走路')
}
Human.prototype.rest=function(){
console.log(this.name+'正在休息')
}
原型继承:
原型链
缺点:所有的属性值都和Human对象一样
Student.prototype=new Human("继承",21)
Student.prototype.study=function(){
console.log(this.name+"正在学习")
}
var t1=new Student("张三",18)
console.log(t1)
console.log(t1.name)
t1.study()
var t2=new Student("李四",21)
console.log(t2)
冒充继承:
通过改变this的指向性,实现的继承方法
缺点:无法继承原型,只是调用了一次函数
function Teacher(name, age) {
//在构造函数中,将Human的属性都挂载过来
//改变this的指向性
Human.call(this, name, age) //this指向 window
}
Teacher.prototype.class = function () {
console.log(this.name + "讲课")
}
var d1 = new Teacher("诸葛亮", 38)
console.log(d1) //没有属性、Human中的this并没有指向 new创建的对象
d1.class()
d1.rest()//调用原型失败
注:
this对象指向:指向对象
函数调用:this指向三种
1.由new调用,指向构造函数创建出来的对象
2.在window下调用,window对象
3.对象中调用或者事件过程中调用, 指向调用的对象
组合继承:
function parent(name, age, a) {
this.a = a //将Human的属性都挂载过来
Human.call(this, name, age) //让Human中的this和parent中this相同
}
parent.prototype = new Human()
parent.prototype.work = function () {
console.log(this.name + "在工作")
}
var c1 = new parent("father", 40)
console.log(c1)
c1.work()
c1.rest()