原型继承
将父类的对象赋值给子类的原型
function Animal(){
this.name = "动物";
this.attribute = "能动";
}
var animal = new Animal(); // 实例化动物类,得到动物对象
function Dog(){
this.jiao = "汪汪";
}
Dog.prototype = animal; // 将狗类的原型赋值为动物对象
function Pig(){
this.jiao = "哼哼";
}
Pig.prototype=animal; // 将猪类的原型赋值为动物对象
var ergou = new Dog();
console.log(ergou.name); // 访问狗对象的name属性 - 动物
var xiaohuang = new Pig();
console.log(xiaohuang.name); // 访问猪对象的name属性 - 动物
借用函数继承
把父类构造函数体借过来使用一下
function Animal(){
this.name = "动物";
}
Animal.prototype.dong=function(){ // 将父类方法绑定到子类上
console.log("能动");
}
function Dog(){
Animal.call(this); // 将父类借用一下,并将函数的this原来是父类改变成子类
this.jiao = '汪汪';
}
var ergou = new Dog();
console.log(ergou.name); // 访问子类的name属性- 动物
ergou.dong(); // 调用dong方法,报错不存在这个方法
借用函数继承有一个缺点:不能继承父类原型上的方法,所以在借用函数继承的基础上在进行原型的方式继承
混合继承
就是把原型继承和借用构造函数继承两个方法组合到一起
function Animal(){
this.name = "动物";
}
Animal.prototype.dong=function(){ // 将父类方法绑定到子类上
console.log("能动");
}
function Dog(){
Animal.call(this); // 将父类借用一下,并将函数的this原来是父类改变成子类
this.jiao = '汪汪';
}
Dog.prototype=new Animal();
var ergou = new Dog();
console.log(ergou.name); // 访问子类的name属性- 动物、
ergou.dong(); // 调用dong方法,也能访问了
es6的继承
在es6之前,可以说没有类这个概念,es6新增了定义类(构造函数的方式)
语法:
class Animal{
}
var animal = new Animal();
console.log(animal); // Animal {}
这种方式定义的类,也必须和new配合使用。
如果实例化需要传递参数的话,就在这个类中,写一个函数,名字必须是constructor
class Animal{
constructor(name){
this.name = name;
}
}
var animal = new Animal("动物");
console.log(animal); // Animal {name: "动物"}
要给类添加一个方法,就像写constructor一样写一个函数,这种写法和我们之前给构造函数的原型添加方法是一样的
class Animal{
constructor(name){
this.name = name;
}
dong(){
console.log("能动");
}
}
var animal = new Animal("动物");
console.log(animal); // Animal {name: "动物"}
animal.dong(); // 能动
这种方式的类继承很容易,而且固定语法:
class 子类 extends 父类{
constructor(){
super();
}
}
例:
class Animal{
constructor(name){
this.name = name;
}
dong(){
console.log("能动");
}
}
class Dog extends Animal{
constructor(name){
super(name);
this.jiao = "汪汪";
}
}
var ergou = new Dog("狗");
console.log(ergou); // Dog {name: "狗", jiao: "汪汪"}
ergou.dong(); // 能动
总结:继承就是让一个类拥有另一个类的属性和方法。