一个类里面的JS getter和setter?

Kub*_*lik 9 javascript getter setter getter-setter

我想在JS中创建一个使用本机getter和setter的类.我知道我可以为对象创建getter/setter,如下所示:

var obj = {
    get value(){
        return this._value;
    },
    set value(val){
        this._value = val;
    }
}
Run Code Online (Sandbox Code Playgroud)

我也知道我可以this.__defineGetter__在一个类/函数中使用,但是MDN说使用__defineGetter__()等是不合适的.

是否有更好的方法将getter和setter添加到js类中:

function class(){
};

class.prototype = {
   get value(){
        //....

}
Run Code Online (Sandbox Code Playgroud)

use*_*006 13

2019 年:ES6 万岁!

class Person {
    
    get name() {
        return this._name + '!!!'
    }

    set name(newValue) {
        this._name = newValue
    }

    constructor(name) {
        this._name = name
    }
}

const me = new Person('Zach')
console.log(me.name)            // Zach!!!

me.name = 'Jacob'
console.log(me.name)            // Jacob!!!

// Of course, _name is not actually private.
console.log(me._name)           // Jacob
Run Code Online (Sandbox Code Playgroud)

  • 如果您正在寻找真正的私有字段,请查看[此处](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Class_fields)。截至 2020 年 4 月 30 日,私有类领域仍处于 TC39 第 3 阶段,但已经在相当多的平台上获得了支持,**特别是自 v 12.0 以来的 NodeJS**。 (2认同)

Mat*_*ato 10

在类上定义属性的最简洁方法是通过Object.defineProperties.这允许您在一个易于阅读的块中定义所有属性.这是一个例子:

var MyClass = function() {
    this._a = undefined;
    this._b = undefined;
};

Object.defineProperties(MyClass.prototype, {
    //Create a read-only property
    a : {
        get : function() {
            return this._a;
        }
    },
    //Create a simple read-write property
    b : {
        get : function() {
            return this._b;
        },
        set : function(value) {
            this._b = value;
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

定义属性时有许多其他选项,因此请务必查看我发布的链接以获取更多信息.同样重要的是要记住,即使是最基本的getter/setter属性也只能与当前浏览器中的方法调用一样快,因此它们可能成为性能密集型情况的瓶颈.


use*_*946 -2

这个实现怎么样:

function makeObject(obj, name) {
    // The property
    var value;

    // The setter
    obj["get" + name] = function() {return value;};

    // The getter
    obj["set" + name] = function(v) {
        value = v;
    };
}
Run Code Online (Sandbox Code Playgroud)

去体验:

var obj = {};
makeObject(obj, "Name");
obj.setName("Lolo");
print(obj.getName());
Run Code Online (Sandbox Code Playgroud)

当然,您可以name在存储之前测试有效性value。测试可以作为makeObject函数的附加参数提供。