Return 这在静态函数中 class

Return this in static function class

我有两个对象,我想做单例class然后这样调用它们Row.init([789]).render() .在第一种情况下,我尝试了它的工作原理:

var Row = (function (options) {
        console.log(options);
        this.data = [123];
        this.render = function () {console.log(this.data);}
        this.init = function (data) {
            this.data = data;
            return this;
        }
        return this;
    })();

但在第二种情况下:

class Row {
    constructor() {
        this.data = {};
    }
    static init(data) {
        this.data = data;
        return this;
    }
    fill() {
        return this;
    }
    render() {
        console.log(this.data);
    }
}

它不能调用 render 方法,我认为它不适合我 return。我如何解决它?在第一种情况下,如何传递选项参数?

当你使用class时,它不再是单例。您需要在 init 函数中创建一个实例:

class Row {
    constructor() {
        this.data = {};
    }
    static init(data) {
        return new this(data);
    }
    fill() {
        return this;
    }
    render() {
        console.log(this.data);
    }
}