一、继承的概念
一个类型的实例能够访问另外一个类型的属性和方法
二、实现继承的几种方式
主要有构造函数继承、原型继承、组合继承、寄生组合继承、原型链继承、ES6继承;实现继承的代码如下:
(1)构造函数继承
<script>
function Person(name, age) {
this.name = name;
this.age = age;
}
function Male(name, age) {
Person.call(this, name, age);
}
var male = new Male('yangyang', 20);
console.log(male.name, male.age);
</script>
(2)原型继承
<script type="text/javascript">
function Person(){
}
Person.prototype.name = "john";
Person.prototype.age = 20;
Person.prototype.sayHello = function(){
console.log(this.name);
}
function Male(){
}
/* Male.prototype = Person.prototype;//有瑕疵,地址相同
Male.prototype.sexy = "nan";*/
/*for(var i in Person.prototype){
Male.prototype[i] = Person.prototype[i]
}*/
//让一个类型的原型对象等于另外一个类型的实例
Male.prototype = new Person();
var male = new Male();
male.sayHello();
var person = new Person();
console.log(person.sexy);
</script>
(3)组合继承:构造函数继承和原型继承的组合
<script type="text/javascript">
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 = new Person();
//只需实现原型方法的继承
for(var i in Person.prototype){
Male.prototype[i] = Person.prototype[i];
}
var male = new Male("john",20);
male.sayHello();
</script>
(4)寄生组合继承
<script type="text/javascript">
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();
</script>
(5)原型链继承
<script type="text/javascript">
function Person(){}
Person.prototype.name = "john";
function Male(){}
Male.prototype = new Person();
var male = new Male();
A.prototype = new B();
B.prototype = new C();
var a = new A();
</script>
(6)ES6继承
<script type="text/javascript">
//也叫语法糖
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
sayHello(){
console.log(this.name);
}
static foo(){ //类方法
console.log("aa");
}
}
class Male extends Person{
constructor(name,age){
super(name,age);//创建this对象,改变this指向,super指向父类的构造函数的
this.sexy = "nan";
}
sayHi(){
super.sayHello();//指向父类的原型对象
}
static bar(){
super.foo();//指向父类
}
}
var male = new Male("john",20);
male.sayHi();
Person.foo();
Male.bar();
</script>