面向对象的三大特性
面向对象的三大特性
封装(抽取内容封装),继承(子类继承父类),多态(重写,重载)
继承:子类继承父类的内容,子类可以拥有父类的所有的非私有的属性及方法
原型继承
构造函数继承 === 继承属性
原型继承 === 继承方法与属性
组合继承 == 构造函数继承 + 原型继承
原型继承
// 原型继承
function Person()
{
this.name = 'lucy'
}
function Son(){
}
Son.prototype = new Person();
console.log(new Son().name); //lucy
组合继承
//组合继承
function Person(){
this.name = 'rosy'
}
function Son(){
Person.apply(this);
}
Son.prototype = new Person();
console.log(new Son().name); //rosy
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.say = function(){
console.log(this.name,"hello");
}
function Student(name,age,grade){
//继承Person那个构造函数已有的属性
//将当前的this指向传给Person,并传属性给Person
//以下两种方法均只继承了属性,并不能继承方法
// Person.call(this,name,age)
Person.apply(this,[name,age])
this.grade = grade;
}
//原型里会获取Person的所有,包括属性与方法,但是属性不影响
// 因为在访问属性时会先访问对象自己身上的,没访问到才会去访问原型的
//原型继承
Student.prototype = new Person();
// 也可以在这基础上继续增加方法
Student.prototype.printGrade = function(){
console.log(this.name,"成绩:" ,this.grade)
}
//也可以覆盖从父类继承原方法,但是会完全覆盖
// Student.prototype.say = function(){
// console.log(this.name,"你好");
// }
// 增强原继承方法,不能取与原方法相同的函数名
Student.prototype.say2 = function(){
// 执行原方法
this.say();
console.log(this.name,"你好");
}
var obj = new Student('yule',18,100);
console.log(obj);
obj.printGrade();
obj.say2();
ES6继承
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
say(){
console.log(this.name,"hello");
}
}
//继承Person类 用extends关键词
class Student extends Person{
constructor(name,age,grade){
//继承父类的属性,要写在最前面
super(name,age);
this.grade = grade;
}
say()
{
//使用父类的同名方法
super.say();
console.log(this.name,"你好")
}
}
var st1 = new Student('yule',18,98);
console.log(st1);
st1.say();
多态
概念:一个东西的多种形态体现,子类是父类多态的体现(基于继承的),重写和重载
重载:同一个类里面有多个同名的方法(覆盖 JS没有重载)
**重写:子类重写父类的方法