Reputation: 85545
var obj = {
get foo(){//Why can't I use argument ^!^
return 'getter';
},
set foo(value){
console.log('setter: '+value);
}
}
> obj.foo = 'bla'
setter: bla
>obj.foo
'getter'
So, I wanted to get the value of foo when it is set:
>obj.foo = 'bla'
setter: bla
>obj.foo
getter: bla
Using like this:
get foo(value){//but alas, I can't use any argument in getter
return 'getter: '+value;
}
Can we not get the value what we set after? I think I'm not understanding the usage of accessor, why do we use it specially for?
Upvotes: 4
Views: 148
Reputation: 14982
You need setters/getters, when you need implement some non-standart logic for property.
For example, next object accumulate all assignments:
var obj = {
_a:0,
get a(){ return this._a;},
set a(value){this._a+=value;}
}
obj.a = 5;
obj.a = 7;
obj.a
12
Also this useful, when you want to write some proxy object,
for example getter resolves data from remote server, and setter post your data to it.
If you need simple property, just use
{a:0}
instead of
{_a:0,get a(){return this._a;},set a(v){this._a=v;}}
Other snippet, with js 'privates':
function Obj(key) {
var private = 0;
var authorized = false;
return {
set token(v) {authorized = (v===key);},
set data(v) {if(authorized) private = v;}
get data() {return authorized?private:undefined;}
}
}
obj = new Obj('pass');
obj.data = 5; // no effect
obj.token = 'pass';
obj.data = 'Data'; //Now works!
///...
Upvotes: 0
Reputation: 2500
The getter is there simply to apply additional logic during all assignments to that property. As a getter
, it doesn't make sense for it to receive a parameter, since there's no opportunity to pass one during the get operation.
If you want the getter
and setter
to use the current value of the property, what you need to do is store it somewhere that it is accessible to both getter and setter.
This could be on the same object, on a different object, or via a closure referenced variable.
var obj = {
get foo(){
return this.___foo___
},
set foo(value){
this.___foo___ = value;
}
}
So now the get
and set
are just a controlled access to the ___foo___
property.
Upvotes: 0
Reputation: 12705
may be this would explain it more to you
var obj = {
get foo(){
console.log('getter');
return this._foo;},
set foo(v){
console.log('setter');
this._foo = v;
}
}
while getting a value from the object passing a parameter wont mean anything.
while setting a value passing a parameter would mean and represent the value that needs to be set.
Chrome console. AFter initializing the object
obj.foo = "UI"
setter
"UI"
obj.foo
getter
"UI"
Upvotes: 2