Getter 和 setter 没有成员

Getter and setter without members

我们可以在不为成员定义方法的情况下使用 getter 和 setter 吗?

例如,改造这个

class int {
    set value(val) {
        this._value = val | 0; // Truncate
    }
    get value() {
        return this._value;
    }
}

var x = new int();

x.value = 5 / 2;
console.log(x.value); // shows 2 instead of 2.5

像这样:

class int {
    set (val) {
        this = val | 0; // Truncate
    }
    get () {
        return this;
    }
}

var x = new int();

x = 5 / 2;
console.log(x); // shows 2 instead of 2.5

当变量的值(x 在您的情况下)被替换 为新值时,您无法进行任何操作。那不是 JavaScript 所拥有的。即使使用代理也无法做到这一点。

您对 int 的第一个定义可能与您将要得到的差不多。

人们尝试了各种方法来获得像您的 int 这样原始的东西。 None 真的很满意。例如,这是一个不常见的尝试:

class Int {
    constructor(value) {
        Object.defineProperty(this, "value", {
            value: value | 0,
            enumerable: true
        });
    }
    set(value) {
        return new this.constructor[Symbol.species](value);
    }
    valueOf() {
        return this.value;
    }
    toString() {
        return this.value; // Even though it's not a string
    }
    static get [Symbol.species]() {
        return this;
    }
}

然后:

let n = new Int(5);
console.log(`n = ${n}`); // n = 5
n = n.set(n / 2);
console.log(`n = ${n}`); // n = 2

但是一旦你做了一些不强制原始的事情,比如:

console.log(n);

你看到了它的客观性。你必须做:

console.log(+n);

这使它成为一把相当大的步兵枪,尽管不变性有助于 let m = n..

示例:

class Int {
    constructor(value) {
        Object.defineProperty(this, "value", {
            value: value | 0,
            enumerable: true
        });
    }
    set(value) {
        return new this.constructor[Symbol.species](value);
    }
    valueOf() {
        return this.value;
    }
    toString() {
        return this.value; // Even though it's not a string
    }
    static get [Symbol.species]() {
        return this;
    }
}

let n = new Int(5);
console.log(`n = ${n}`); // n = 5
n = n.set(n / 2);
console.log(`n = ${n}`); // n = 2

// But
console.log(n); // (object representation of it)