JS中的继承(包括ES6里继承)

1 篇文章 0 订阅

 原生 JS 中的类、静态方法、继承
常见的继承方法有原型链继承、对象冒充继承
但两者各有缺点

原型链继承:可以继承构造函数里面以及原型链上面的属性和方法,实例化子类的时候没法给父类传参
对象冒充继承:没法继承原型链上面的属性和方法

类和属性和方法
function  Person(name,age) {
    this.name=name;
    this.age=age;
    this.run=function(){
        console.log(this.name+'---'+this.age);
    }
}
Person.setName=function(){
       console.log('静态方法');
    }//静态方法
var p=new Person('zhangsan','20');//实例方法
 

实例方法和静态方法的区别:
实例方法是通过实例化来调用的,静态是通过类名直接调用

var p=new Person('zhangsan','20');  
 p.run();
 p.work();

 Person.setName();  /*执行静态方法*/

先看原型链继承

function  Person(name,age) {
    this.name=name;
    this.age=age;
    this.run=function(){
        console.log(this.name+'---'+this.age);
    }
}
Person.prototype.work=function(){
    console.log('work');
}

function Web(name,age){
}

Web.prototype=new Person();
var w=new Web('李四',20);
w.run();
w.work();//undefined---undefined
		//work

没法实例化

再看对象冒充继承

function  Person(name,age) {
    this.name=name;
    this.age=age;
    this.run=function(){
        console.log(this.name+'---'+this.age);
    }
}
Person.prototype.work=function(){
    console.log('work');
}

function Web(name,age){
    Person.call(this,name,age);  
}


var w=new Web('李四',20);
w.run();
w.work(); //李四---20
		//w.work is not a function

为了避免这两种的弊端

结合

function  Person(name,age) {
    this.name=name;
    this.age=age;
    this.run=function(){
        console.log(this.name+'---'+this.age);
    }
}
Person.prototype.work=function(){
    console.log('work');
}

function Web(name,age){
    Person.call(this,name,age);  
}
Web.prototype=new Person();

var w=new Web('李四',20);
w.run();
w.work();
//李四---20
//work 

ES6继承

ES6里面的类的写法

class Person{
    constructor(name,age){
        this.name=name;
        this.age=age;
    }
    getInfo(){
        console.log(`姓名:${this.name} 年龄:${this.age}`);
    }
    run(){
        console.log('run')
    }
}

它的继承是借助了extends

class Web extends Person{ //web继承了Person
    constructor(name,age,sex){
        super(name,age);   /*实例化子类的时候把子类的数据传给父类*/
        this.sex=sex;
    }
    print(){

        console.log(this.sex);
    }
}
var w=new Web('张三','30','男');
w.getInfo();
w.print();
//姓名:张三 年龄:30
//男
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值