js重新讲解继承,es5的一些继承,es6继承的改变 ----------由浅入深

es5 利用原型公有私有继承

function Parent(name) {
    this.name = name
}
Parent.prototype.home = '北京';
function Child() {
    this.age = 8;
}
//将父类的实例绑定在子类的原型上
Child.prototype = new Parent('aa');
//实例化原型
let child = new Child();
//这时候继承父类的公有私有属性
console.log(child.home+child.name);
// 结果 北京 + aa

es5 私有继承,改变this指向,公有不继承


function Parent(name) {
this.name = name
}
//父类的公有属性
Parent.prototype.home = '北京';


function Child(name) {
this.age = 8;
Parent.call(this,...arguments);


}
let child = new Child('hello');
console.log(child.home+child.name);
//结果是 undefined +hello

 

es5继承公有属性,私有属性不继承

function Parent(name) {
    this.name = name
}
Parent.prototype.home = '北京';
function Child() {
    this.age = 8;
}
Child.prototype = Object.create(Parent.prototype);
let child = new Child();
//这时候继承只继承父类的公有属性 父类的私有属性没有继承
console.log(child.home+child.name);
// 结果 北京 + indefined

 

es6 继承,私有公有都继承extend//定义一个类

class Person {
    //控制器
    constructor(name,age){
        this.name=name;
        this.age=age;
    }
    eat(){
        console.log("吃饭");
    }
}
//只继承共有的

//关键字 extends 公私有都会继承
class Girl extends  Person{
    constructor(name,age){
        super(name,age); //默认调用父类,并且this就是girl实例
    }
}
let g=new Girl('aa',18);
console.log(g.name,g.age);
g.eat();
//结果
aa 18

//
吃饭
 

 node继承  利用util模块  

inherits

function Parent(name) {
    this.name = name
}
Parent.prototype.home = '北京';
function Child() {
    this.age = 8;
}
// es5 里面判断数据类型
// indexof
// instanceof
// constuctor
// Object.prototype.toString.call

//util 判断数据类型
console.log(util.isArray({}));
//继承使用util里的方法 inherits
util.inherits(Child,Parent);

 

posted @ 2017-09-12 11:55  八bug哥哥  阅读(455)  评论(2编辑  收藏  举报