ES6的class 中 constructor 方法

ES6 的 class 属于一种“语法糖”,让写法更像面对对象的编程。

function Abc(x, y) {
    this.x = x;
    this.y = y;
}
Abc.prototype.add = function() {
    return this.x + this.y;
}

等同于

class Abc {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    add() {
        return this.x + this.y;
    }
}

 

constructor 方法是类的构造函数,是一个默认方法,通过 new 命令创建对象实例时,自动调用该方法。一个类必须有 constructor 方法,如果没有显式定义,一个默认的 consructor 方法会被默认添加。所以即使你没有添加构造函数,也是会有一个默认的构造函数的。一般 constructor 方法返回实例对象 this ,但是也可以指定 constructor 方法返回一个全新的对象,让返回的实例对象不是该类的实例。

原文链接:https://blog.csdn.net/qq_41916378/article/details/109714768

posted @ 2022-08-28 10:47  风的方向·  阅读(581)  评论(0编辑  收藏  举报