es5和es6类、静态、和继承方法区别

本文对比了ES5和ES6中类的定义、继承方式及静态方法的使用。ES5通过构造函数和原型链实现类和继承,而ES6引入了更简洁的class语法,并通过extends关键字实现继承。同时,ES6提供了更直观的静态方法定义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

es5

1.es5中的类和静态方法

function Person(name,age) {
       //构造函数里面的方法和属性
       this.name=name;
       this.age=age;
       this.run=function(){
           console.log(`${this.name}---${this.age}`)
       }
   }
   //原型链上面的属性和方法可以被多个实例共享
   Person.prototype.sex='男';
   Person.prototype.work=function(){
       console.log(`${this.name}---${this.age}---${this.sex}`);
   }
   //静态方法
   Person.setName=function(){
       console.log('静态方法');
   }
    /*实例方法是通过实例化来调用的,静态是通过类名直接调用*/
   var p=new Person('zhangsan','20');  
   p.run();
   p.work();
   Person.setName();  /*执行静态方法*/

2.原型链继承和对象冒充继承

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();  //w.work is not a function

es6

//定义Person类
class Person{
   constructor(name,age) {   /*类的构造函数,实例化的时候执行,new的时候执行*/
       this._name=name;
       this._age=age;
   }
   getName(){
       console.log(this._name);

   }
   setName(name){
       this._name=name
   }
}
var p=new Person('张三1','20');
p.getName();
p.setName('李四');
p.getName();

//es6里面的继承

 class Person{
   constructor(name,age){
       this.name=name;
       this.age=age;
   }
   getInfo(){
       console.log(`姓名:${this.name} 年龄:${this.age}`);
   }
   run(){
       console.log('run')
   }
}
class Web extends Person{  //继承了Person     extends          super(name,age);
   constructor(name,age,sex){
       super(name,age);   /*实例化子类的时候把子类的数据传给父类*/
       this.sex=sex;
   }
   print(){

       console.log(this.sex);
   }
}
var w=new Web('张三','30','男');
w.getInfo();

//es6里面的静态方法

class Person{

    constructor(name){

        this._name=name;  /*属性*/
    }
    run(){  /*实例方法*/

        console.log(this._name);
    }
    static work(){   /*静态方法*/
        console.log('这是es6里面的静态方法');
    }
}
Person.instance='这是一个静态方法的属性';


var p=new  Person('张三');

p.run();
Person.work(); /es6里面的静态方法/

console.log(Person.instance);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值