原型继承:
function Person(name,age){
this.name= name;
this.age = age;
}
Person.prototype.sayHello=function(){
console.log(this.name);
}
var person = new Person("zs",10);
person.sayHello();解释:原型对象上的属性和方法能够被实例访问到
function Person(name,age){
this.name= name;
this.age=age;
}
Person.prototype.sayHello=function(){
console.log(this.name);
}
function Male(){
}
Male.prototype=new Person("张三",10);//Male的原型对象等于peson的实例
var male = new Male();
male.sayHello();解释:male上有指Male原型对象的内部指针,Male的原型对象上有指向Persn原型对象的内部指针。
缺点:每一个的实例只有相同的属性值
组合继承:
function Animal(name,age){
this.name = name;
this.age = age;
}
Animal.prototype.sayHello=function(){
console.log("aaa");
}
Animal.prototype.sayHello=function(){
console.log("bb");
}
function Cat(name,age){
Animal.call(this,name,age);//属性继承
}
function Dog(name,age){
Animal.call(this,name,age);
}
// Cat.prototype=Animal.prototype;//赋值赋 的是地址 所以父类能访问到子类的方法
// var cat = new Cat();
// cat.sayHello();//改进方法
for(var i in Animal.prototype){
Cat.prototype[i]=Animal.prototype[i];//原型方法继承
}
Cat.prototype.sayHi =function(){
console.log("小猫");
}
var cat = new Cat();
var animal = new Animal();
cat.sayHello();
cat.sayHi();
animal.sayHi();//
寄生式继承
function Perosn(name,age){
this.name = name;
this.age = age;
}
function Male(name,age){
Person.call(this,name,age);
}
function inhert(Sub,Super){
Sub.prototype=Object.create(Super.prototype);
Sub.prototype.constructor=Sub;//更改构造函数的指向 构造函数里有原型对象,原型对象有指构造函数的指针
}
inhert(Male,Person);
var male = new Male("20",10);
class继承 es6里的继承
class Person{
constructor(name,age){
this.name=name;
this.age=age;
}
}
class Male extends Person{
constructor(name,age,sexy){
super(name,age,sexy);
this.sexy=sexy;
}
}
var male = new Male("z",1,"男");
console.log(male.name,male.age,male.sexy);