对一个对象使用getter/setter有什么意义吗



在我看来,对类内的对象使用getter和setter毫无意义。据我所知,get/set很有用,因为它可以防止类外的人更改不应该更改的内容或将其更改为不应该更改。然而,这对对象来说似乎毫无意义。例如,我有一个人有一个地址,我想阻止编辑地址,你只能查看它:

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"
});

但你仍然可以这样编辑:

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

为了防止这种情况,我认为您必须返回对象的副本,而不是引用。然而,据我所知,没有标准的方法来深度克隆对象。因此,您要么必须浅层克隆它,如果您有很多嵌套引用,这似乎并不理想,要么只返回对对象的引用,该引用可以编辑。

我是不是遗漏了什么?

考虑这个类。

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);
}

用";Setter";可以控制初始化属性。你可以看到,改变";boo";财产,但任何试图改变";foo";将引发异常。

用";Getter";可以控制检索属性的值。您可以看到,检索"0"的值是可能的;foo";属性但不是";boo";它的价值是私人的。

PS:以下是一些示例,可以更好地理解JS对对象和数组的行为:

//This works fine:
//Object
const obj = {};
obj.foo = 'bar';
console.log(obj); // {foo : 'bar'}
obj.foo = 'bar2';
console.log(obj); // {foo : 'bar2'}  
//---------------------------------------
//Array:
const arr = [];
arr.push('foo');
console.log(arr); // ['foo']
arr.unshift("foo2");
console.log(arr); // ['foo2', 'foo']
arr.pop();
console.log(arr); // ['foo2']
//===========================================
//but these won't work:
const obj = {};
obj = {foo: 'bar'}; // error - re-assigning
const arr = ['foo'];
const arr = ['bar']; // error - re-declaring
const foo = 'bar'; 
foo = 'bar2';       // error - can not re-assign
var foo = 'bar3';   // error - already declared
function foo() {};  // error - already declared

新示例:

class A {
constructor(val) {
this._foo = val;
}
set foo(val) {
throw new Error("It's not possible to change the foo property!")
}
get foo() {
return this._foo;
}
}
class B {
constructor(val) {
this._obj = new A(val);
}
get Obj() {
return this._obj;
}
}
let b = new B('Test');
b.Obj.foo = 'new value';
console.log(b.Obj.foo);

以这种方式,不可能更改值​​内部对象的。

相关内容

最新更新