1. 构造函数的继承
function Person(name,age){
this.name = name,
this.age= age,
this.sayHello = function(){
Person.call(this,name);
}
}
function Male(name,age){
Person.call(this,name,age);
this.sexy = "male";
}
var male = new Male("john",20);
console.log(male);
2. 原型继承
function Person(){}
Person.prototype.name = "john";
Person.prototype.age = 20;
Person.protoype.sayHello = function(){
console.log(this.name);
}
function Male(){}
Male.prototype = new Person();
Male.prototype.sexy = "male";
var male = new Male();
console.log(male.sexy);
3. 组合继承
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function(){
console.log(this.name);
}
function Male(){
Person.call(this,name,age);
}
for(let i in Person.prototype){
Male.prototype[i] = Person.prototype[i];
}
Male.protype.sexy = "male";
var male = new Male("john",20);
male.sayHello();
4. 寄生式组合继承
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function(){
console.log(this.name);
}
function Male(name,age){
Person.call(this,name,age);
}
Male.prototype = Object.create(Person.prototype);
Male.prototype.constructor = Male;
var male = new Male("john",20);
male.sayHello();
console.log(male.__proto__.constructor);
function inherit(Sup,Sub){
Sub.prototype = Object.create(Sup.prototype);
Sub.prototype.constructor = Sub;
}
5. ES6继承
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
sayHello(){
console.log(this.name)
}
static foo(){
console.log("foo");
}
}
class Male extends Person{
constructor(name,age){
super(name,age)
this.sexy = 'male';
}
sayHi(){
console.log("hi");
super.sayHello();
}
static bar(){
super.foo();
}
}
var male = new Male("john",20);
male.sayHello();
male.sayHi();
Male.bar();