1. 旧的构造函数写法

  • 编写构造函数

function Cat(name) {
    this.name = name;
}

Cat.prototype.conlog = function () {
    console.log(this.name);
};

var c = new Cat('cat');
c.conlog();

  • 继承

function Cat(name) {
    this.name = name;
}

Cat.prototype.conlog = function () {
    console.log(this.name);
};

function Dog(name) {
    Cat.call(this, name);  // 执行Cat并且改变指向;
}

/* 继承 */
function Fn() {
}

Fn.prototype = Cat.prototype;
Dog.prototype = new Fn();


var c = new Cat('cat');
c.conlog();

var d = new Dog('dog');
d.conlog();

2. 的构造函数写法

  • 编写构造函数

// 固定写法

class 构造函数名{
/* constructor是关键字是定义构造函数本身-定义私有属性的地方 */
    constructor(参数){
        this.私有属性名 = 参数;
    }

/* 定义公共属性和函数 */
公共函数方法名(){

    }

/* 定义静态方法 */
    static 静态函数名(){
// 可以外部直接调用不需要 new
    }
}

class Long {
/* constructor是关键字是定义构造函数本身-定义私有属性的地方 */
    constructor(name) {
        this.name = name;
    }

/* 定义公共属性和函数 */
    conlog() {
        console.log(this.name);
    }

    returnnam() {
        return this.name;
    }

// 新增的静态的方法,可以直接调用,不用 new -> Long.getcolor('#fff');
    static getcolor(color) {
        console.log(color);
    }
}

let l = new Long('龙');
l.conlog();
Long.getcolor('#fff');  // 调用静态方法可以不用new;

  • 继承

// 固定写法

class 构造函数名 extends 继承的函数名{
    constructor(参数){
        super(参数);  // super指的是父类意思
    }

公共函数方法名(){
        super.父类方法();  // 调用父类的方法;
    }
}

class Long {
/* constructor是关键字是定义构造函数本身-定义私有属性的地方 */
    constructor(name) {
        this.name = name;
    }

/* 定义公共属性和函数 */
    conlog() {
        console.log(this.name);
    }

    returnnam() {
        return this.name;
    }

// 新增的静态的方法,可以直接调用,不用 new -> Long.getcolor('#fff');
    static getcolor(color) {
        console.log(color);
    }
}

/* extends继承 */
class Phoenix extends Long {
    constructor(name) {
        super(name);  // super指的是父类( 因为继承了Long所以要将Phoenix的name传给Long);
    }

    static getcolor(color) {
        super.getcolor(color);  // 执行父类的getcolor静态方法
    }

    getname() {
        let name = super.returnnam();  // 调用父类的方法(super.父类函数名);
        console.log(name);
    }
}

let l = new Long('龙');
l.conlog();
Long.getcolor('#fff');  // 调用静态方法可以不用new;

let p = new Phoenix('凤凰');
p.conlog();
p.getname();
Phoenix.getcolor('#000');  // 执行父类的getcolor静态方法