JavaScript 定义 类

时间:2023-03-09 13:20:25
JavaScript 定义 类

JavaScript 定义 类

一 构建类的原则

构造函数 等于 原型的constructor

    //构造函数
    function Hero(name,skill){
        this.name = name;
        this.skill = skill;
    }
    //原型
    Hero.prototype;

    //构造函数 === 原型的constructor
    Hero === Hero.prototype.constructor;    //=>true

    //实例均继承原型

二构建类的方法:

1.直接使用构造方法

该方法创建实例会将内容给每个类都创建一份

//实例属性方法都声明在构造器里
function Hero(name,skill){
    this.name = name;
    this.skill = skill;
    this.sayHello = function(){
        console.log(this.name + ";" + this.skill);
    }
}
//类静态常量
Hero.common = '都有特别的事迹';
//类静态方法
Hero.doSomething = function(){
    console.log('doSomething');
}
var saber = new Hero ('Saber','Excalibur');
saber.sayHello();

var archer = new Hero('Archer','Unlimit Blade Work');
archer.sayHello();

//此处为每个对象都拷贝了一份sayHello 方法 会浪费内存空间
saber.sayHello == archer.sayHello;//=>false

2.优化构造器方法--将方法函数移到构造器的prototype

  • 每个实例都会有一个__proto__属性指向构造函数的prototype
  • 这样每个实例在当前找不到方法后会到prototype寻找该方法
  • 能避免之前出现的拷贝多个方法的情况

2.1扩展prototype

//实例属性方法都声明在构造器里
function Hero(name,skill){
    this.name = name;
    this.skill = skill;
}
Hero.prototype.sayHello = function(){
    console.log(this.name + ";" + this.skill);
}

//类静态常量
Hero.common = '都有特别的事迹';
//类静态方法
Hero.doSomething = function(){
    console.log('doSomething');
}
var saber = new Hero ('Saber','Excalibur');
saber.sayHello();

var archer = new Hero('Archer','Unlimit Blade Work');
archer.sayHello();

saber.sayHello == archer.sayHello;//=>true
    

2.2重写prototype

//实例属性方法都声明在构造器里
function Hero(name,skill){
    this.name = name;
    this.skill = skill;
}

Hero.prototype = {
    //保持 构造函数 等于 原型的constructor
    constructor:Hero,
    sayHello:function(){
        console.log(this.name + ";" + this.skill);
    }
}

//类静态常量
Hero.common = '都有特别的事迹';
//类静态方法
Hero.doSomething = function(){
    console.log('doSomething');
}