Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

javascript - Is there any point to use getters/setters for an object?

It seems to me that using getters and setters for an object inside a class has no point to it. As I understand it, get/set is useful because it prevents someone outside the class changing something that shouldn't be changed or changing it to something it shouldn't be. However it seems pointless for objects. For example, I have a person with an address, I want to prevent editing the address, you can only view it:

class Person{
    constructor(name, address){
        this._name = name;
        this._address = address;
    }

    get address(){
        return this._address;
    }
}

let bob = new Person("bob", {
    street: "123 Main Street",
    city: "Los Angelos",
    state: "California"
});

But then you can still edit it like this:

let address = bob.address;
address.state = "New York";

To prevent this, I would think that you have to return a copy of the object instead of the reference. However, as far as i know, there is no standard way to deep clone an object. So you either have to shallow clone it, which seems not ideal if you have lots of nested references, or just return the reference to the object, which can be edited.

Am I missing something here?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Consider this class.

class Test {
    constructor(val) {
        this._foo = val;
    }

    set foo(val) {
        throw new Error("It's not possible to change the foo property!")
    }

    set boo(val) {
        console.log("setting _boo")
        this._boo = val;
    }

    get foo() {
        console.log("getting _foo");
        return this._foo;
    }
}

try {
    let test = new Test('foooooo');
    test.boo = "booooo";
    console.log(`foo: ${test.foo}`);
    test.foo = "bar";
} catch (e) {
    console.log(e);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...